@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 +12 -0
- package/README.md +44 -0
- package/dist/index.cjs +137 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +129 -42
- package/dist/index.d.ts +129 -42
- package/dist/index.js +135 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -148,6 +148,36 @@ declare class SMSAdapter extends BasePlatformAdapter {
|
|
|
148
148
|
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
149
149
|
}
|
|
150
150
|
|
|
151
|
+
/**
|
|
152
|
+
* `smsChannel` — the SMS channel (Twilio backend only) described as data.
|
|
153
|
+
*
|
|
154
|
+
* Typed locally on purpose: the object is structurally a `ChannelDescriptor`, but a published
|
|
155
|
+
* `.d.ts` naming a core type must not break a consumer on an older peer floor.
|
|
156
|
+
*/
|
|
157
|
+
|
|
158
|
+
/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */
|
|
159
|
+
interface ConfigField {
|
|
160
|
+
readonly key: string;
|
|
161
|
+
readonly required: boolean;
|
|
162
|
+
readonly secret: boolean;
|
|
163
|
+
readonly env: string;
|
|
164
|
+
readonly description: string;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* The SMS channel on the Twilio backend. `transport` is `"socket"` as the issue requires; inbound
|
|
168
|
+
* messages still arrive through a webhook the app hosts (see the README).
|
|
169
|
+
*
|
|
170
|
+
* `create` validates each value with this package's `ConfigurationError` and makes no network call.
|
|
171
|
+
*
|
|
172
|
+
* @public
|
|
173
|
+
*/
|
|
174
|
+
declare const smsChannel: {
|
|
175
|
+
platform: "sms";
|
|
176
|
+
transport: "socket";
|
|
177
|
+
config: readonly ConfigField[];
|
|
178
|
+
create(config: Readonly<Record<string, unknown>>): SMSAdapter;
|
|
179
|
+
};
|
|
180
|
+
|
|
151
181
|
/**
|
|
152
182
|
* Typed errors for `@theokit/gateway-sms` (D389-D396).
|
|
153
183
|
*
|
|
@@ -298,47 +328,6 @@ declare function normalizeE164(input: string, defaultCountry?: string): string;
|
|
|
298
328
|
*/
|
|
299
329
|
declare function splitForSMS(text: string, limit?: number): string[];
|
|
300
330
|
|
|
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
331
|
/**
|
|
343
332
|
* The SMS half of a channel webhook, in the shape a framework webhook seam expects.
|
|
344
333
|
*
|
|
@@ -411,4 +400,102 @@ interface VerifiableAdapter {
|
|
|
411
400
|
*/
|
|
412
401
|
declare function smsWebhookVerifier(adapter: SMSAdapter | VerifiableAdapter, opts?: SMSWebhookVerifierOptions): (request: Request) => Promise<WebhookVerifyResult>;
|
|
413
402
|
|
|
414
|
-
|
|
403
|
+
/**
|
|
404
|
+
* Standalone Twilio request verifier.
|
|
405
|
+
*
|
|
406
|
+
* Twilio signs voice webhooks exactly like SMS webhooks: `X-Twilio-Signature` is the base64
|
|
407
|
+
* HMAC-SHA1 (keyed with the auth token) of the full URL followed by every POST parameter, sorted by
|
|
408
|
+
* name, as `name + value`. No adapter and no `twilio` SDK are needed.
|
|
409
|
+
*
|
|
410
|
+
* @public
|
|
411
|
+
*/
|
|
412
|
+
|
|
413
|
+
/** Options for {@link twilioRequestVerifier}. @public */
|
|
414
|
+
interface TwilioRequestVerifierOptions {
|
|
415
|
+
/** The Twilio auth token the signature is keyed with. */
|
|
416
|
+
readonly authToken: string;
|
|
417
|
+
/**
|
|
418
|
+
* The URL Twilio POSTs to, as Twilio sees it. Defaults to the request URL, which behind a proxy
|
|
419
|
+
* or tunnel is the internal one and will not match.
|
|
420
|
+
*/
|
|
421
|
+
readonly publicUrl?: string;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Build a verifier for Twilio webhooks (SMS or voice).
|
|
425
|
+
*
|
|
426
|
+
* The request body is READ; pass a clone if it is needed afterwards.
|
|
427
|
+
*
|
|
428
|
+
* @public
|
|
429
|
+
*/
|
|
430
|
+
declare function twilioRequestVerifier(opts: TwilioRequestVerifierOptions): (request: Request) => Promise<WebhookVerifyResult>;
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Minimal TwiML builders. Every text node and attribute value is XML-escaped.
|
|
434
|
+
*
|
|
435
|
+
* @public
|
|
436
|
+
*/
|
|
437
|
+
/**
|
|
438
|
+
* TwiML verb builders for Twilio voice webhooks. Each returns an XML string; combine them with
|
|
439
|
+
* `twiml.response`.
|
|
440
|
+
*
|
|
441
|
+
* @public
|
|
442
|
+
*/
|
|
443
|
+
declare const twiml: {
|
|
444
|
+
say(text: string, opts?: {
|
|
445
|
+
voice?: string;
|
|
446
|
+
language?: string;
|
|
447
|
+
}): string;
|
|
448
|
+
gather(opts: {
|
|
449
|
+
action: string;
|
|
450
|
+
input?: "speech" | "dtmf";
|
|
451
|
+
timeoutSeconds?: number;
|
|
452
|
+
prompt?: string;
|
|
453
|
+
}): string;
|
|
454
|
+
redirect(url: string): string;
|
|
455
|
+
hangup(): string;
|
|
456
|
+
/** Wrap verbs in `<Response>`. Verbs must come from the builders above. */
|
|
457
|
+
response(...verbs: string[]): string;
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* `createWebhookServer` — Express helper for inbound SMS webhooks.
|
|
462
|
+
*
|
|
463
|
+
* Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)
|
|
464
|
+
* each with the matching parser middleware. All three:
|
|
465
|
+
*
|
|
466
|
+
* 1. Read the raw body verbatim (signature verification depends on the
|
|
467
|
+
* exact bytes — even one extra `\r\n` invalidates the HMAC).
|
|
468
|
+
* 2. Call `adapter.verifySignature(ctx)` → 401 if false.
|
|
469
|
+
* 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.
|
|
470
|
+
* 4. Return 204 No Content.
|
|
471
|
+
*
|
|
472
|
+
* Caller can pass an existing Express app (`opts.app`) or let the helper
|
|
473
|
+
* create one. `start()` / `stop()` are idempotent.
|
|
474
|
+
*
|
|
475
|
+
* @public
|
|
476
|
+
*/
|
|
477
|
+
|
|
478
|
+
interface WebhookServerOptions {
|
|
479
|
+
readonly adapter: SMSAdapter;
|
|
480
|
+
/** Mount path prefix; default `"/sms"`. The full path is `${path}/${backend}`. */
|
|
481
|
+
readonly path?: string;
|
|
482
|
+
/** Listen port. Ignored when `app` is provided. Default `3000`. */
|
|
483
|
+
readonly port?: number;
|
|
484
|
+
/** Inject an existing Express app instead of creating one. */
|
|
485
|
+
readonly app?: Express;
|
|
486
|
+
}
|
|
487
|
+
/** A started HTTP listener, with the handle needed to shut it down again. */
|
|
488
|
+
interface WebhookServer {
|
|
489
|
+
start(): Promise<void>;
|
|
490
|
+
stop(): Promise<void>;
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Build the HTTP listener that receives the provider's inbound-SMS callbacks.
|
|
494
|
+
*
|
|
495
|
+
* The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the
|
|
496
|
+
* provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project
|
|
497
|
+
* that only sends messages never pays for it.
|
|
498
|
+
*/
|
|
499
|
+
declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
|
|
500
|
+
|
|
501
|
+
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, smsChannel, 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 {
|
|
@@ -630,6 +631,65 @@ function secretFromOpts(opts) {
|
|
|
630
631
|
}
|
|
631
632
|
}
|
|
632
633
|
|
|
634
|
+
// src/channel.ts
|
|
635
|
+
var KEYS = ["accountSid", "authToken", "fromNumber", "publicUrl"];
|
|
636
|
+
function readString(config, key) {
|
|
637
|
+
const value = config[key];
|
|
638
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
639
|
+
throw new ConfigurationError({
|
|
640
|
+
code: "invalid_config",
|
|
641
|
+
message: `gateway-sms: config.${key} must be a non-empty string`,
|
|
642
|
+
detail: key
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
return value;
|
|
646
|
+
}
|
|
647
|
+
var CONFIG = [
|
|
648
|
+
{
|
|
649
|
+
key: "accountSid",
|
|
650
|
+
required: true,
|
|
651
|
+
secret: false,
|
|
652
|
+
env: "SMS_ACCOUNT_SID",
|
|
653
|
+
description: "The Twilio account SID."
|
|
654
|
+
},
|
|
655
|
+
{
|
|
656
|
+
key: "authToken",
|
|
657
|
+
required: true,
|
|
658
|
+
secret: true,
|
|
659
|
+
env: "SMS_AUTH_TOKEN",
|
|
660
|
+
description: "The Twilio auth token; also verifies inbound signatures."
|
|
661
|
+
},
|
|
662
|
+
{
|
|
663
|
+
key: "fromNumber",
|
|
664
|
+
required: true,
|
|
665
|
+
secret: false,
|
|
666
|
+
env: "SMS_FROM_NUMBER",
|
|
667
|
+
description: "The bot's own E.164 number, used as the sender."
|
|
668
|
+
},
|
|
669
|
+
{
|
|
670
|
+
key: "publicUrl",
|
|
671
|
+
required: true,
|
|
672
|
+
secret: false,
|
|
673
|
+
env: "SMS_PUBLIC_URL",
|
|
674
|
+
description: "The public URL Twilio posts inbound messages to."
|
|
675
|
+
}
|
|
676
|
+
];
|
|
677
|
+
var smsChannel = {
|
|
678
|
+
platform: "sms",
|
|
679
|
+
transport: "socket",
|
|
680
|
+
config: CONFIG,
|
|
681
|
+
create(config) {
|
|
682
|
+
const [accountSid, authToken, fromNumber, publicUrl] = KEYS.map((k) => readString(config, k));
|
|
683
|
+
return new SMSAdapter({
|
|
684
|
+
backend: "twilio",
|
|
685
|
+
accountSid,
|
|
686
|
+
authToken,
|
|
687
|
+
fromNumber,
|
|
688
|
+
publicUrl
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
};
|
|
692
|
+
|
|
633
693
|
// src/parse-inbound.ts
|
|
634
694
|
function parseInbound(options, ctx) {
|
|
635
695
|
const backend = createBackend(options);
|
|
@@ -642,6 +702,80 @@ function parseInbound(options, ctx) {
|
|
|
642
702
|
if (inbound.messageId === "") return null;
|
|
643
703
|
return inboundToMessageEvent(inbound, options.backend);
|
|
644
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
|
+
// src/twiml.ts
|
|
749
|
+
var ILLEGAL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;
|
|
750
|
+
function esc(s) {
|
|
751
|
+
return s.replace(ILLEGAL, "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
752
|
+
}
|
|
753
|
+
function attrs(a) {
|
|
754
|
+
let out = "";
|
|
755
|
+
for (const [k, v] of Object.entries(a)) {
|
|
756
|
+
if (v !== void 0) out += ` ${k}="${esc(String(v))}"`;
|
|
757
|
+
}
|
|
758
|
+
return out;
|
|
759
|
+
}
|
|
760
|
+
var twiml = {
|
|
761
|
+
say(text, opts = {}) {
|
|
762
|
+
return `<Say${attrs({ voice: opts.voice, language: opts.language })}>${esc(text)}</Say>`;
|
|
763
|
+
},
|
|
764
|
+
gather(opts) {
|
|
765
|
+
const a = attrs({ action: opts.action, input: opts.input, timeout: opts.timeoutSeconds });
|
|
766
|
+
return opts.prompt === void 0 ? `<Gather${a}/>` : `<Gather${a}>${twiml.say(opts.prompt)}</Gather>`;
|
|
767
|
+
},
|
|
768
|
+
redirect(url) {
|
|
769
|
+
return `<Redirect>${esc(url)}</Redirect>`;
|
|
770
|
+
},
|
|
771
|
+
hangup() {
|
|
772
|
+
return "<Hangup/>";
|
|
773
|
+
},
|
|
774
|
+
/** Wrap verbs in `<Response>`. Verbs must come from the builders above. */
|
|
775
|
+
response(...verbs) {
|
|
776
|
+
return `<?xml version="1.0" encoding="UTF-8"?><Response>${verbs.join("")}</Response>`;
|
|
777
|
+
}
|
|
778
|
+
};
|
|
645
779
|
async function loadExpress() {
|
|
646
780
|
return loadPeer(
|
|
647
781
|
async () => import('express'),
|
|
@@ -722,6 +856,6 @@ function smsWebhookVerifier(adapter, opts = {}) {
|
|
|
722
856
|
};
|
|
723
857
|
}
|
|
724
858
|
|
|
725
|
-
export { BackendNotInstalledError, ConfigurationError, SMSAdapter, createWebhookServer, normalizeE164, parseInbound, smsWebhookVerifier, splitForSMS };
|
|
859
|
+
export { BackendNotInstalledError, ConfigurationError, SMSAdapter, createWebhookServer, normalizeE164, parseInbound, smsChannel, smsWebhookVerifier, splitForSMS, twilioRequestVerifier, twiml };
|
|
726
860
|
//# sourceMappingURL=index.js.map
|
|
727
861
|
//# sourceMappingURL=index.js.map
|