@theokit/gateway-sms 0.3.3 → 0.4.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/dist/index.d.cts CHANGED
@@ -298,47 +298,6 @@ declare function normalizeE164(input: string, defaultCountry?: string): string;
298
298
  */
299
299
  declare function splitForSMS(text: string, limit?: number): string[];
300
300
 
301
- /**
302
- * `createWebhookServer` — Express helper for inbound SMS webhooks.
303
- *
304
- * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)
305
- * each with the matching parser middleware. All three:
306
- *
307
- * 1. Read the raw body verbatim (signature verification depends on the
308
- * exact bytes — even one extra `\r\n` invalidates the HMAC).
309
- * 2. Call `adapter.verifySignature(ctx)` → 401 if false.
310
- * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.
311
- * 4. Return 204 No Content.
312
- *
313
- * Caller can pass an existing Express app (`opts.app`) or let the helper
314
- * create one. `start()` / `stop()` are idempotent.
315
- *
316
- * @public
317
- */
318
-
319
- interface WebhookServerOptions {
320
- readonly adapter: SMSAdapter;
321
- /** Mount path prefix; default `"/sms"`. The full path is `${path}/${backend}`. */
322
- readonly path?: string;
323
- /** Listen port. Ignored when `app` is provided. Default `3000`. */
324
- readonly port?: number;
325
- /** Inject an existing Express app instead of creating one. */
326
- readonly app?: Express;
327
- }
328
- /** A started HTTP listener, with the handle needed to shut it down again. */
329
- interface WebhookServer {
330
- start(): Promise<void>;
331
- stop(): Promise<void>;
332
- }
333
- /**
334
- * Build the HTTP listener that receives the provider's inbound-SMS callbacks.
335
- *
336
- * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the
337
- * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project
338
- * that only sends messages never pays for it.
339
- */
340
- declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
341
-
342
301
  /**
343
302
  * The SMS half of a channel webhook, in the shape a framework webhook seam expects.
344
303
  *
@@ -411,4 +370,102 @@ interface VerifiableAdapter {
411
370
  */
412
371
  declare function smsWebhookVerifier(adapter: SMSAdapter | VerifiableAdapter, opts?: SMSWebhookVerifierOptions): (request: Request) => Promise<WebhookVerifyResult>;
413
372
 
414
- export { BackendNotInstalledError, ConfigurationError, type PlivoOptions, SMSAdapter, type SMSAdapterOptions, type SMSWebhookVerifierOptions, type TwilioOptions, type VonageOptions, type WebhookServer, type WebhookServerOptions, type WebhookVerifyResult, createWebhookServer, normalizeE164, parseInbound, smsWebhookVerifier, splitForSMS };
373
+ /**
374
+ * Standalone Twilio request verifier.
375
+ *
376
+ * Twilio signs voice webhooks exactly like SMS webhooks: `X-Twilio-Signature` is the base64
377
+ * HMAC-SHA1 (keyed with the auth token) of the full URL followed by every POST parameter, sorted by
378
+ * name, as `name + value`. No adapter and no `twilio` SDK are needed.
379
+ *
380
+ * @public
381
+ */
382
+
383
+ /** Options for {@link twilioRequestVerifier}. @public */
384
+ interface TwilioRequestVerifierOptions {
385
+ /** The Twilio auth token the signature is keyed with. */
386
+ readonly authToken: string;
387
+ /**
388
+ * The URL Twilio POSTs to, as Twilio sees it. Defaults to the request URL, which behind a proxy
389
+ * or tunnel is the internal one and will not match.
390
+ */
391
+ readonly publicUrl?: string;
392
+ }
393
+ /**
394
+ * Build a verifier for Twilio webhooks (SMS or voice).
395
+ *
396
+ * The request body is READ; pass a clone if it is needed afterwards.
397
+ *
398
+ * @public
399
+ */
400
+ declare function twilioRequestVerifier(opts: TwilioRequestVerifierOptions): (request: Request) => Promise<WebhookVerifyResult>;
401
+
402
+ /**
403
+ * Minimal TwiML builders. Every text node and attribute value is XML-escaped.
404
+ *
405
+ * @public
406
+ */
407
+ /**
408
+ * TwiML verb builders for Twilio voice webhooks. Each returns an XML string; combine them with
409
+ * `twiml.response`.
410
+ *
411
+ * @public
412
+ */
413
+ declare const twiml: {
414
+ say(text: string, opts?: {
415
+ voice?: string;
416
+ language?: string;
417
+ }): string;
418
+ gather(opts: {
419
+ action: string;
420
+ input?: "speech" | "dtmf";
421
+ timeoutSeconds?: number;
422
+ prompt?: string;
423
+ }): string;
424
+ redirect(url: string): string;
425
+ hangup(): string;
426
+ /** Wrap verbs in `<Response>`. Verbs must come from the builders above. */
427
+ response(...verbs: string[]): string;
428
+ };
429
+
430
+ /**
431
+ * `createWebhookServer` — Express helper for inbound SMS webhooks.
432
+ *
433
+ * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)
434
+ * each with the matching parser middleware. All three:
435
+ *
436
+ * 1. Read the raw body verbatim (signature verification depends on the
437
+ * exact bytes — even one extra `\r\n` invalidates the HMAC).
438
+ * 2. Call `adapter.verifySignature(ctx)` → 401 if false.
439
+ * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.
440
+ * 4. Return 204 No Content.
441
+ *
442
+ * Caller can pass an existing Express app (`opts.app`) or let the helper
443
+ * create one. `start()` / `stop()` are idempotent.
444
+ *
445
+ * @public
446
+ */
447
+
448
+ interface WebhookServerOptions {
449
+ readonly adapter: SMSAdapter;
450
+ /** Mount path prefix; default `"/sms"`. The full path is `${path}/${backend}`. */
451
+ readonly path?: string;
452
+ /** Listen port. Ignored when `app` is provided. Default `3000`. */
453
+ readonly port?: number;
454
+ /** Inject an existing Express app instead of creating one. */
455
+ readonly app?: Express;
456
+ }
457
+ /** A started HTTP listener, with the handle needed to shut it down again. */
458
+ interface WebhookServer {
459
+ start(): Promise<void>;
460
+ stop(): Promise<void>;
461
+ }
462
+ /**
463
+ * Build the HTTP listener that receives the provider's inbound-SMS callbacks.
464
+ *
465
+ * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the
466
+ * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project
467
+ * that only sends messages never pays for it.
468
+ */
469
+ declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
470
+
471
+ export { BackendNotInstalledError, ConfigurationError, type PlivoOptions, SMSAdapter, type SMSAdapterOptions, type SMSWebhookVerifierOptions, type TwilioOptions, type TwilioRequestVerifierOptions, type VonageOptions, type WebhookServer, type WebhookServerOptions, type WebhookVerifyResult, createWebhookServer, normalizeE164, parseInbound, smsWebhookVerifier, splitForSMS, twilioRequestVerifier, twiml };
package/dist/index.d.ts CHANGED
@@ -298,47 +298,6 @@ declare function normalizeE164(input: string, defaultCountry?: string): string;
298
298
  */
299
299
  declare function splitForSMS(text: string, limit?: number): string[];
300
300
 
301
- /**
302
- * `createWebhookServer` — Express helper for inbound SMS webhooks.
303
- *
304
- * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)
305
- * each with the matching parser middleware. All three:
306
- *
307
- * 1. Read the raw body verbatim (signature verification depends on the
308
- * exact bytes — even one extra `\r\n` invalidates the HMAC).
309
- * 2. Call `adapter.verifySignature(ctx)` → 401 if false.
310
- * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.
311
- * 4. Return 204 No Content.
312
- *
313
- * Caller can pass an existing Express app (`opts.app`) or let the helper
314
- * create one. `start()` / `stop()` are idempotent.
315
- *
316
- * @public
317
- */
318
-
319
- interface WebhookServerOptions {
320
- readonly adapter: SMSAdapter;
321
- /** Mount path prefix; default `"/sms"`. The full path is `${path}/${backend}`. */
322
- readonly path?: string;
323
- /** Listen port. Ignored when `app` is provided. Default `3000`. */
324
- readonly port?: number;
325
- /** Inject an existing Express app instead of creating one. */
326
- readonly app?: Express;
327
- }
328
- /** A started HTTP listener, with the handle needed to shut it down again. */
329
- interface WebhookServer {
330
- start(): Promise<void>;
331
- stop(): Promise<void>;
332
- }
333
- /**
334
- * Build the HTTP listener that receives the provider's inbound-SMS callbacks.
335
- *
336
- * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the
337
- * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project
338
- * that only sends messages never pays for it.
339
- */
340
- declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
341
-
342
301
  /**
343
302
  * The SMS half of a channel webhook, in the shape a framework webhook seam expects.
344
303
  *
@@ -411,4 +370,102 @@ interface VerifiableAdapter {
411
370
  */
412
371
  declare function smsWebhookVerifier(adapter: SMSAdapter | VerifiableAdapter, opts?: SMSWebhookVerifierOptions): (request: Request) => Promise<WebhookVerifyResult>;
413
372
 
414
- export { BackendNotInstalledError, ConfigurationError, type PlivoOptions, SMSAdapter, type SMSAdapterOptions, type SMSWebhookVerifierOptions, type TwilioOptions, type VonageOptions, type WebhookServer, type WebhookServerOptions, type WebhookVerifyResult, createWebhookServer, normalizeE164, parseInbound, smsWebhookVerifier, splitForSMS };
373
+ /**
374
+ * Standalone Twilio request verifier.
375
+ *
376
+ * Twilio signs voice webhooks exactly like SMS webhooks: `X-Twilio-Signature` is the base64
377
+ * HMAC-SHA1 (keyed with the auth token) of the full URL followed by every POST parameter, sorted by
378
+ * name, as `name + value`. No adapter and no `twilio` SDK are needed.
379
+ *
380
+ * @public
381
+ */
382
+
383
+ /** Options for {@link twilioRequestVerifier}. @public */
384
+ interface TwilioRequestVerifierOptions {
385
+ /** The Twilio auth token the signature is keyed with. */
386
+ readonly authToken: string;
387
+ /**
388
+ * The URL Twilio POSTs to, as Twilio sees it. Defaults to the request URL, which behind a proxy
389
+ * or tunnel is the internal one and will not match.
390
+ */
391
+ readonly publicUrl?: string;
392
+ }
393
+ /**
394
+ * Build a verifier for Twilio webhooks (SMS or voice).
395
+ *
396
+ * The request body is READ; pass a clone if it is needed afterwards.
397
+ *
398
+ * @public
399
+ */
400
+ declare function twilioRequestVerifier(opts: TwilioRequestVerifierOptions): (request: Request) => Promise<WebhookVerifyResult>;
401
+
402
+ /**
403
+ * Minimal TwiML builders. Every text node and attribute value is XML-escaped.
404
+ *
405
+ * @public
406
+ */
407
+ /**
408
+ * TwiML verb builders for Twilio voice webhooks. Each returns an XML string; combine them with
409
+ * `twiml.response`.
410
+ *
411
+ * @public
412
+ */
413
+ declare const twiml: {
414
+ say(text: string, opts?: {
415
+ voice?: string;
416
+ language?: string;
417
+ }): string;
418
+ gather(opts: {
419
+ action: string;
420
+ input?: "speech" | "dtmf";
421
+ timeoutSeconds?: number;
422
+ prompt?: string;
423
+ }): string;
424
+ redirect(url: string): string;
425
+ hangup(): string;
426
+ /** Wrap verbs in `<Response>`. Verbs must come from the builders above. */
427
+ response(...verbs: string[]): string;
428
+ };
429
+
430
+ /**
431
+ * `createWebhookServer` — Express helper for inbound SMS webhooks.
432
+ *
433
+ * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)
434
+ * each with the matching parser middleware. All three:
435
+ *
436
+ * 1. Read the raw body verbatim (signature verification depends on the
437
+ * exact bytes — even one extra `\r\n` invalidates the HMAC).
438
+ * 2. Call `adapter.verifySignature(ctx)` → 401 if false.
439
+ * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.
440
+ * 4. Return 204 No Content.
441
+ *
442
+ * Caller can pass an existing Express app (`opts.app`) or let the helper
443
+ * create one. `start()` / `stop()` are idempotent.
444
+ *
445
+ * @public
446
+ */
447
+
448
+ interface WebhookServerOptions {
449
+ readonly adapter: SMSAdapter;
450
+ /** Mount path prefix; default `"/sms"`. The full path is `${path}/${backend}`. */
451
+ readonly path?: string;
452
+ /** Listen port. Ignored when `app` is provided. Default `3000`. */
453
+ readonly port?: number;
454
+ /** Inject an existing Express app instead of creating one. */
455
+ readonly app?: Express;
456
+ }
457
+ /** A started HTTP listener, with the handle needed to shut it down again. */
458
+ interface WebhookServer {
459
+ start(): Promise<void>;
460
+ stop(): Promise<void>;
461
+ }
462
+ /**
463
+ * Build the HTTP listener that receives the provider's inbound-SMS callbacks.
464
+ *
465
+ * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the
466
+ * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project
467
+ * that only sends messages never pays for it.
468
+ */
469
+ declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
470
+
471
+ export { BackendNotInstalledError, ConfigurationError, type PlivoOptions, SMSAdapter, type SMSAdapterOptions, type SMSWebhookVerifierOptions, type TwilioOptions, type TwilioRequestVerifierOptions, type VonageOptions, type WebhookServer, type WebhookServerOptions, type WebhookVerifyResult, createWebhookServer, normalizeE164, parseInbound, smsWebhookVerifier, splitForSMS, twilioRequestVerifier, twiml };
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { GatewayConfigurationError, BasePlatformAdapter, rawBodyCapture, DEFAULT_WEBHOOK_MAX_BYTES, listenerLifecycle, chunkByGrapheme, splitKeepingRows, loadPeer } from '@theokit/gateway';
2
2
  import { parsePhoneNumberFromString } from 'libphonenumber-js';
3
+ import { timingSafeEqual, createHmac } from 'crypto';
3
4
 
4
5
  // src/adapter.ts
5
6
  var ConfigurationError = class extends GatewayConfigurationError {
@@ -642,6 +643,80 @@ function parseInbound(options, ctx) {
642
643
  if (inbound.messageId === "") return null;
643
644
  return inboundToMessageEvent(inbound, options.backend);
644
645
  }
646
+ function decode(s) {
647
+ return decodeURIComponent(s.replace(/\+/g, " "));
648
+ }
649
+ function parseForm(body) {
650
+ const out = [];
651
+ for (const pair of body.split("&")) {
652
+ if (pair.length === 0) continue;
653
+ const eq = pair.indexOf("=");
654
+ out.push([decode(eq < 0 ? pair : pair.slice(0, eq)), decode(eq < 0 ? "" : pair.slice(eq + 1))]);
655
+ }
656
+ return out;
657
+ }
658
+ function compare(a, b) {
659
+ if (a === b) return 0;
660
+ return a < b ? -1 : 1;
661
+ }
662
+ function sign(authToken, url, pairs) {
663
+ const sorted = [...pairs].sort((x, y) => compare(x[0], y[0]) || compare(x[1], y[1]));
664
+ let data = url;
665
+ for (const [k, v] of sorted) data += k + v;
666
+ return createHmac("sha1", authToken).update(data, "utf8").digest("base64");
667
+ }
668
+ function twilioRequestVerifier(opts) {
669
+ return async (request) => {
670
+ const header = request.headers.get("x-twilio-signature");
671
+ if (header === null || header.length === 0) {
672
+ return { ok: false, reason: "missing X-Twilio-Signature header" };
673
+ }
674
+ let pairs;
675
+ try {
676
+ pairs = parseForm(await request.text());
677
+ } catch {
678
+ return { ok: false, reason: "unparseable body" };
679
+ }
680
+ const expected = Buffer.from(sign(opts.authToken, opts.publicUrl ?? request.url, pairs));
681
+ const actual = Buffer.from(header);
682
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
683
+ return { ok: false, reason: "signature mismatch" };
684
+ }
685
+ return { ok: true };
686
+ };
687
+ }
688
+
689
+ // src/twiml.ts
690
+ var ILLEGAL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
691
+ function esc(s) {
692
+ return s.replace(ILLEGAL, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
693
+ }
694
+ function attrs(a) {
695
+ let out = "";
696
+ for (const [k, v] of Object.entries(a)) {
697
+ if (v !== void 0) out += ` ${k}="${esc(String(v))}"`;
698
+ }
699
+ return out;
700
+ }
701
+ var twiml = {
702
+ say(text, opts = {}) {
703
+ return `<Say${attrs({ voice: opts.voice, language: opts.language })}>${esc(text)}</Say>`;
704
+ },
705
+ gather(opts) {
706
+ const a = attrs({ action: opts.action, input: opts.input, timeout: opts.timeoutSeconds });
707
+ return opts.prompt === void 0 ? `<Gather${a}/>` : `<Gather${a}>${twiml.say(opts.prompt)}</Gather>`;
708
+ },
709
+ redirect(url) {
710
+ return `<Redirect>${esc(url)}</Redirect>`;
711
+ },
712
+ hangup() {
713
+ return "<Hangup/>";
714
+ },
715
+ /** Wrap verbs in `<Response>`. Verbs must come from the builders above. */
716
+ response(...verbs) {
717
+ return `<?xml version="1.0" encoding="UTF-8"?><Response>${verbs.join("")}</Response>`;
718
+ }
719
+ };
645
720
  async function loadExpress() {
646
721
  return loadPeer(
647
722
  async () => import('express'),
@@ -722,6 +797,6 @@ function smsWebhookVerifier(adapter, opts = {}) {
722
797
  };
723
798
  }
724
799
 
725
- export { BackendNotInstalledError, ConfigurationError, SMSAdapter, createWebhookServer, normalizeE164, parseInbound, smsWebhookVerifier, splitForSMS };
800
+ export { BackendNotInstalledError, ConfigurationError, SMSAdapter, createWebhookServer, normalizeE164, parseInbound, smsWebhookVerifier, splitForSMS, twilioRequestVerifier, twiml };
726
801
  //# sourceMappingURL=index.js.map
727
802
  //# sourceMappingURL=index.js.map