@theokit/gateway-sms 0.1.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.js ADDED
@@ -0,0 +1,661 @@
1
+ import { BasePlatformAdapter } from '@theokit/gateway';
2
+ import { parsePhoneNumberFromString } from 'libphonenumber-js';
3
+
4
+ // src/adapter.ts
5
+
6
+ // src/errors.ts
7
+ var ConfigurationError = class extends Error {
8
+ name = "ConfigurationError";
9
+ code;
10
+ detail;
11
+ constructor(opts) {
12
+ super(opts.message ?? `gateway-sms: ${opts.code}`);
13
+ this.code = opts.code;
14
+ this.detail = opts.detail;
15
+ }
16
+ };
17
+ var BackendNotInstalledError = class extends ConfigurationError {
18
+ constructor(backend, pkgName) {
19
+ super({
20
+ code: "backend_not_installed",
21
+ message: `gateway-sms: peer-dep "${pkgName}" not installed but backend="${backend}" was selected. Run: pnpm add ${pkgName}`,
22
+ detail: pkgName
23
+ });
24
+ }
25
+ };
26
+ function normalizeE164(input, defaultCountry) {
27
+ if (input.length === 0) {
28
+ throw new ConfigurationError({
29
+ code: "invalid_phone_number",
30
+ message: "gateway-sms: phone number is empty",
31
+ detail: "<empty>"
32
+ });
33
+ }
34
+ const parsed = parsePhoneNumberFromString(
35
+ input,
36
+ defaultCountry
37
+ );
38
+ if (parsed === void 0 || !parsed.isValid()) {
39
+ throw new ConfigurationError({
40
+ code: "invalid_phone_number",
41
+ message: `gateway-sms: invalid phone number ${JSON.stringify(input)}`,
42
+ detail: input
43
+ });
44
+ }
45
+ return parsed.format("E.164");
46
+ }
47
+
48
+ // src/backend/plivo.ts
49
+ async function loadPlivo() {
50
+ try {
51
+ const mod = await import('plivo');
52
+ return mod;
53
+ } catch {
54
+ throw new BackendNotInstalledError("plivo", "plivo");
55
+ }
56
+ }
57
+ var PlivoBackend = class {
58
+ constructor(opts) {
59
+ this.opts = opts;
60
+ }
61
+ opts;
62
+ kind = "plivo";
63
+ mod;
64
+ client;
65
+ async connect() {
66
+ if (this.client !== void 0) return true;
67
+ this.mod = await loadPlivo();
68
+ this.client = new this.mod.Client(this.opts.authId, this.opts.authToken);
69
+ return true;
70
+ }
71
+ async disconnect() {
72
+ this.client = void 0;
73
+ }
74
+ verifySignature(ctx) {
75
+ if (this.mod?.validateV3Signature === void 0) return false;
76
+ const signature = ctx.headers["x-plivo-signature-v3"];
77
+ const nonce = ctx.headers["x-plivo-signature-v3-nonce"];
78
+ if (signature === void 0 || nonce === void 0) return false;
79
+ try {
80
+ return this.mod.validateV3Signature("POST", ctx.url, nonce, this.opts.authToken, signature);
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+ parseInbound(ctx) {
86
+ let params = {};
87
+ if ((ctx.headers["content-type"] ?? "").includes("application/json")) {
88
+ try {
89
+ params = JSON.parse(ctx.rawBody);
90
+ } catch {
91
+ params = {};
92
+ }
93
+ } else {
94
+ params = parseFormUrlEncoded(ctx.rawBody);
95
+ }
96
+ return {
97
+ from: normalizeE164(params.From ?? "", this.opts.defaultCountry),
98
+ to: normalizeE164(params.To ?? "", this.opts.defaultCountry),
99
+ body: params.Text ?? params.text ?? "",
100
+ messageId: params.MessageUUID ?? params.message_uuid ?? "",
101
+ receivedAt: Date.now(),
102
+ raw: params
103
+ };
104
+ }
105
+ async sendMessage(to, body) {
106
+ if (this.client === void 0) {
107
+ return {
108
+ ok: false,
109
+ error: { code: "not_connected", message: "PlivoBackend.connect() not called" }
110
+ };
111
+ }
112
+ try {
113
+ const resp = await this.client.messages.create(this.opts.fromNumber, to, body);
114
+ const id = resp.messageUuid?.[0] ?? resp.message_uuid?.[0] ?? resp.apiId ?? "";
115
+ return { ok: true, messageId: id };
116
+ } catch (err) {
117
+ return mapPlivoError(err);
118
+ }
119
+ }
120
+ };
121
+ function parseFormUrlEncoded(body) {
122
+ const params = {};
123
+ for (const pair of body.split("&")) {
124
+ if (pair.length === 0) continue;
125
+ const eqIdx = pair.indexOf("=");
126
+ const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);
127
+ const v = eqIdx < 0 ? "" : pair.slice(eqIdx + 1);
128
+ params[decodeURIComponent(k.replace(/\+/g, " "))] = decodeURIComponent(v.replace(/\+/g, " "));
129
+ }
130
+ return params;
131
+ }
132
+ function mapPlivoError(err) {
133
+ const e = err;
134
+ const status = e.statusCode ?? e.status ?? 0;
135
+ if (status === 429)
136
+ return { ok: false, error: { code: "rate_limit", message: e.message ?? "Plivo rate limit" } };
137
+ if (status === 401 || status === 403) {
138
+ return {
139
+ ok: false,
140
+ error: { code: "permission_denied", message: e.message ?? "Plivo auth error" }
141
+ };
142
+ }
143
+ if (status === 400) {
144
+ return {
145
+ ok: false,
146
+ error: { code: "invalid_request", message: e.message ?? "Plivo rejected request" }
147
+ };
148
+ }
149
+ return {
150
+ ok: false,
151
+ error: {
152
+ code: "send_failed",
153
+ message: e.message ?? (err instanceof Error ? err.message : String(err))
154
+ }
155
+ };
156
+ }
157
+
158
+ // src/backend/twilio.ts
159
+ async function loadTwilio() {
160
+ try {
161
+ const mod = await import('twilio');
162
+ const candidate = mod.default ?? mod;
163
+ return candidate;
164
+ } catch {
165
+ throw new BackendNotInstalledError("twilio", "twilio");
166
+ }
167
+ }
168
+ var TwilioBackend = class {
169
+ constructor(opts) {
170
+ this.opts = opts;
171
+ }
172
+ opts;
173
+ kind = "twilio";
174
+ client;
175
+ twilio;
176
+ async connect() {
177
+ if (this.client !== void 0) return true;
178
+ this.twilio = await loadTwilio();
179
+ this.client = this.twilio(this.opts.accountSid, this.opts.authToken);
180
+ return true;
181
+ }
182
+ async disconnect() {
183
+ this.client = void 0;
184
+ }
185
+ verifySignature(ctx) {
186
+ if (this.twilio === void 0) return false;
187
+ const signature = ctx.headers["x-twilio-signature"];
188
+ if (signature === void 0) return false;
189
+ const params = parseFormUrlEncoded2(ctx.rawBody);
190
+ try {
191
+ return this.twilio.validateRequest(this.opts.authToken, signature, ctx.url, params);
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+ parseInbound(ctx) {
197
+ const params = parseFormUrlEncoded2(ctx.rawBody);
198
+ return {
199
+ from: normalizeE164(params.From ?? "", this.opts.defaultCountry),
200
+ to: normalizeE164(params.To ?? "", this.opts.defaultCountry),
201
+ body: params.Body ?? "",
202
+ messageId: params.MessageSid ?? params.SmsMessageSid ?? "",
203
+ receivedAt: Date.now(),
204
+ raw: params
205
+ };
206
+ }
207
+ async sendMessage(to, body) {
208
+ if (this.client === void 0) {
209
+ return {
210
+ ok: false,
211
+ error: { code: "not_connected", message: "TwilioBackend.connect() not called" }
212
+ };
213
+ }
214
+ try {
215
+ const msg = await this.client.messages.create({ from: this.opts.fromNumber, to, body });
216
+ return { ok: true, messageId: msg.sid };
217
+ } catch (err) {
218
+ return mapTwilioError(err);
219
+ }
220
+ }
221
+ };
222
+ function parseFormUrlEncoded2(body) {
223
+ const params = {};
224
+ for (const pair of body.split("&")) {
225
+ if (pair.length === 0) continue;
226
+ const eqIdx = pair.indexOf("=");
227
+ const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);
228
+ const v = eqIdx < 0 ? "" : pair.slice(eqIdx + 1);
229
+ params[decodeURIComponent(k.replace(/\+/g, " "))] = decodeURIComponent(v.replace(/\+/g, " "));
230
+ }
231
+ return params;
232
+ }
233
+ function mapTwilioError(err) {
234
+ const e = err;
235
+ const status = e.status ?? 0;
236
+ if (status === 429) {
237
+ return { ok: false, error: { code: "rate_limit", message: e.message ?? "Twilio rate limit" } };
238
+ }
239
+ if (status === 401 || status === 403) {
240
+ return {
241
+ ok: false,
242
+ error: { code: "permission_denied", message: e.message ?? "Twilio auth error" }
243
+ };
244
+ }
245
+ if (status === 400) {
246
+ return {
247
+ ok: false,
248
+ error: { code: "invalid_request", message: e.message ?? "Twilio rejected request" }
249
+ };
250
+ }
251
+ return {
252
+ ok: false,
253
+ error: {
254
+ code: "send_failed",
255
+ message: e.message ?? (err instanceof Error ? err.message : String(err))
256
+ }
257
+ };
258
+ }
259
+
260
+ // src/backend/vonage.ts
261
+ async function loadVonage() {
262
+ try {
263
+ const raw = await import('@vonage/server-sdk');
264
+ return raw;
265
+ } catch {
266
+ throw new BackendNotInstalledError("vonage", "@vonage/server-sdk");
267
+ }
268
+ }
269
+ var VonageBackend = class {
270
+ constructor(opts) {
271
+ this.opts = opts;
272
+ }
273
+ opts;
274
+ kind = "vonage";
275
+ mod;
276
+ vonage;
277
+ async connect() {
278
+ if (this.vonage !== void 0) return true;
279
+ this.mod = await loadVonage();
280
+ this.vonage = new this.mod.Vonage({
281
+ apiKey: this.opts.apiKey,
282
+ apiSecret: this.opts.apiSecret,
283
+ signatureSecret: this.opts.signatureSecret
284
+ });
285
+ return true;
286
+ }
287
+ async disconnect() {
288
+ this.vonage = void 0;
289
+ }
290
+ verifySignature(ctx) {
291
+ const auth = ctx.headers.authorization;
292
+ if (auth === void 0) return false;
293
+ const m = auth.match(/^Bearer\s+(.+)$/i);
294
+ if (m === null) return false;
295
+ const token = m[1] ?? "";
296
+ if (token.length === 0) return false;
297
+ if (this.mod?.Auth?.verifySignature === void 0) return false;
298
+ try {
299
+ return this.mod.Auth.verifySignature(token, this.opts.signatureSecret);
300
+ } catch {
301
+ return false;
302
+ }
303
+ }
304
+ parseInbound(ctx) {
305
+ let payload = {};
306
+ try {
307
+ payload = JSON.parse(ctx.rawBody);
308
+ } catch {
309
+ payload = {};
310
+ }
311
+ return {
312
+ from: normalizeE164(payload.msisdn ?? payload.from ?? "", this.opts.defaultCountry),
313
+ to: normalizeE164(payload.to ?? "", this.opts.defaultCountry),
314
+ body: payload.text ?? "",
315
+ messageId: payload.messageId ?? payload["message-id"] ?? "",
316
+ receivedAt: Date.now(),
317
+ raw: payload
318
+ };
319
+ }
320
+ async sendMessage(to, body) {
321
+ if (this.vonage === void 0) {
322
+ return {
323
+ ok: false,
324
+ error: { code: "not_connected", message: "VonageBackend.connect() not called" }
325
+ };
326
+ }
327
+ try {
328
+ const resp = await this.vonage.sms.send({ from: this.opts.fromNumber, to, text: body });
329
+ const msg = resp.messages?.[0];
330
+ const id = msg?.["message-id"] ?? msg?.messageId ?? "";
331
+ if (msg?.status !== void 0 && msg.status !== "0") {
332
+ return {
333
+ ok: false,
334
+ error: { code: "send_failed", message: `Vonage returned status=${msg.status}` }
335
+ };
336
+ }
337
+ return { ok: true, messageId: id };
338
+ } catch (err) {
339
+ return mapVonageError(err);
340
+ }
341
+ }
342
+ };
343
+ function mapVonageError(err) {
344
+ const e = err;
345
+ const status = e.status ?? e.response?.status ?? 0;
346
+ if (status === 429)
347
+ return { ok: false, error: { code: "rate_limit", message: e.message ?? "Vonage rate limit" } };
348
+ if (status === 401 || status === 403) {
349
+ return {
350
+ ok: false,
351
+ error: { code: "permission_denied", message: e.message ?? "Vonage auth error" }
352
+ };
353
+ }
354
+ return {
355
+ ok: false,
356
+ error: {
357
+ code: "send_failed",
358
+ message: e.message ?? (err instanceof Error ? err.message : String(err))
359
+ }
360
+ };
361
+ }
362
+
363
+ // src/backend/index.ts
364
+ function createBackend(opts) {
365
+ switch (opts.backend) {
366
+ case "twilio":
367
+ return new TwilioBackend(opts);
368
+ case "plivo":
369
+ return new PlivoBackend(opts);
370
+ case "vonage":
371
+ return new VonageBackend(opts);
372
+ default: {
373
+ const _exhaustive = opts;
374
+ throw new Error(`unknown backend: ${JSON.stringify(_exhaustive)}`);
375
+ }
376
+ }
377
+ }
378
+
379
+ // src/normalize.ts
380
+ function inboundToMessageEvent(inbound, backend) {
381
+ return {
382
+ id: inbound.messageId,
383
+ platform: "sms",
384
+ sender: { id: inbound.from },
385
+ channel: { id: inbound.from, type: "dm" },
386
+ text: inbound.body,
387
+ receivedAt: inbound.receivedAt,
388
+ sms: {
389
+ backend,
390
+ messageId: inbound.messageId,
391
+ from: inbound.from,
392
+ to: inbound.to,
393
+ raw: inbound.raw
394
+ }
395
+ };
396
+ }
397
+
398
+ // src/split.ts
399
+ var PART_PREFIX_RESERVED = 8;
400
+ function splitForSMS(text, limit = 1600) {
401
+ if (text.length === 0) return [""];
402
+ if (text.length <= limit) return [text];
403
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
404
+ const segments = Array.from(segmenter.segment(text), (s) => s.segment);
405
+ const parts = [];
406
+ const cap = limit - PART_PREFIX_RESERVED;
407
+ let buf = "";
408
+ for (const seg of segments) {
409
+ if (buf.length + seg.length > cap) {
410
+ if (buf.length > 0) parts.push(buf);
411
+ buf = "";
412
+ }
413
+ buf += seg;
414
+ }
415
+ if (buf.length > 0) parts.push(buf);
416
+ if (parts.length === 1) {
417
+ return parts;
418
+ }
419
+ const total = parts.length;
420
+ return parts.map((p, i) => `(${i + 1}/${total}) ${p}`);
421
+ }
422
+
423
+ // src/adapter.ts
424
+ var SMSAdapter = class extends BasePlatformAdapter {
425
+ platform = "sms";
426
+ backend;
427
+ inboundHandler;
428
+ connected = false;
429
+ defaultCountry;
430
+ constructor(opts) {
431
+ super();
432
+ const secret = secretFromOpts(opts);
433
+ if (secret.length === 0) {
434
+ throw new ConfigurationError({
435
+ code: "signing_secret_required",
436
+ message: `gateway-sms: backend="${opts.backend}" requires a signing secret (would accept unsigned webhooks)`
437
+ });
438
+ }
439
+ this.defaultCountry = opts.defaultCountry;
440
+ this.backend = createBackend(opts);
441
+ }
442
+ async connect() {
443
+ if (this.connected) return true;
444
+ const ok = await this.backend.connect();
445
+ this.connected = ok;
446
+ return ok;
447
+ }
448
+ async disconnect() {
449
+ if (!this.connected) return;
450
+ await this.backend.disconnect();
451
+ this.connected = false;
452
+ this.inboundHandler = void 0;
453
+ }
454
+ async sendMessage(out) {
455
+ if (out.text.length === 0) {
456
+ return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
457
+ }
458
+ let toE164;
459
+ try {
460
+ toE164 = normalizeE164(out.channel.id, this.defaultCountry);
461
+ } catch (err) {
462
+ const msg = err instanceof Error ? err.message : String(err);
463
+ return { ok: false, error: { code: "invalid_phone_number", message: msg } };
464
+ }
465
+ const parts = splitForSMS(out.text);
466
+ let lastResult;
467
+ for (const part of parts) {
468
+ lastResult = await this.backend.sendMessage(toE164, part);
469
+ if (lastResult.ok !== true) {
470
+ return {
471
+ ok: false,
472
+ error: {
473
+ code: lastResult.error?.code ?? "partial_send_failure",
474
+ message: `partial send failed after ${parts.indexOf(part)}/${parts.length}: ${lastResult.error?.message ?? "unknown"}`
475
+ }
476
+ };
477
+ }
478
+ }
479
+ return lastResult ?? { ok: false, error: { code: "send_failed", message: "no parts sent" } };
480
+ }
481
+ onInbound(handler) {
482
+ this.inboundHandler = handler;
483
+ return () => {
484
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
485
+ };
486
+ }
487
+ /**
488
+ * Webhook hook — called by `createWebhookServer` AFTER signature
489
+ * verification + parseInbound. Returns dispatch outcome (used for
490
+ * 200/204 vs 500 by the webhook handler).
491
+ *
492
+ * @internal
493
+ */
494
+ async dispatchInbound(ctx) {
495
+ if (!this.backend.verifySignature(ctx)) {
496
+ return "parse_failed";
497
+ }
498
+ let inbound;
499
+ try {
500
+ inbound = this.backend.parseInbound(ctx);
501
+ } catch {
502
+ return "parse_failed";
503
+ }
504
+ if (this.inboundHandler === void 0) return "no_handler";
505
+ const event = inboundToMessageEvent(inbound, this.backend.kind);
506
+ try {
507
+ await this.inboundHandler(event);
508
+ } catch (err) {
509
+ const msg = err instanceof Error ? err.message : String(err);
510
+ process.stderr.write(`[gateway-sms] handler threw: ${msg}
511
+ `);
512
+ }
513
+ return "ok";
514
+ }
515
+ /**
516
+ * Direct signature check — used by the webhook server to respond
517
+ * `401` BEFORE dispatch when signature is invalid.
518
+ *
519
+ * @internal
520
+ */
521
+ verifySignature(ctx) {
522
+ return this.backend.verifySignature(ctx);
523
+ }
524
+ /**
525
+ * Direct parse — used by the webhook server when signature was already
526
+ * validated upstream. Returns the normalized `SMSMessageEvent` to be
527
+ * dispatched.
528
+ *
529
+ * @internal
530
+ */
531
+ buildEventFromCtx(ctx) {
532
+ const inbound = this.backend.parseInbound(ctx);
533
+ return inboundToMessageEvent(inbound, this.backend.kind);
534
+ }
535
+ /**
536
+ * Dispatch a pre-built event (used by webhook server after manual
537
+ * signature + parse). Honors EC-H replace semantics and isolates
538
+ * handler exceptions per `gateway-runner` contract.
539
+ *
540
+ * @internal
541
+ */
542
+ async dispatchEvent(event) {
543
+ if (this.inboundHandler === void 0) return "no_handler";
544
+ try {
545
+ await this.inboundHandler(event);
546
+ } catch (err) {
547
+ const msg = err instanceof Error ? err.message : String(err);
548
+ process.stderr.write(`[gateway-sms] handler threw: ${msg}
549
+ `);
550
+ }
551
+ return "ok";
552
+ }
553
+ /** Backend kind (escape hatch for callers needing to introspect). */
554
+ getBackendKind() {
555
+ return this.backend.kind;
556
+ }
557
+ };
558
+ function secretFromOpts(opts) {
559
+ switch (opts.backend) {
560
+ case "twilio":
561
+ return opts.authToken;
562
+ case "plivo":
563
+ return opts.authToken;
564
+ case "vonage":
565
+ return opts.signatureSecret;
566
+ default: {
567
+ return "";
568
+ }
569
+ }
570
+ }
571
+
572
+ // src/webhook-server.ts
573
+ async function loadExpress() {
574
+ try {
575
+ const mod = await import('express');
576
+ const fn = mod.default ?? mod;
577
+ return { default: fn };
578
+ } catch {
579
+ throw new ConfigurationError({
580
+ code: "express_not_installed",
581
+ message: 'gateway-sms: peer-dep "express" not installed. Run: pnpm add express'
582
+ });
583
+ }
584
+ }
585
+ function buildSignatureContext(req) {
586
+ const rawBody = req.rawBody ?? "";
587
+ const headers = {};
588
+ for (const [k, v] of Object.entries(req.headers)) {
589
+ headers[k.toLowerCase()] = Array.isArray(v) ? v.join(",") : v ?? "";
590
+ }
591
+ const protoHeader = headers["x-forwarded-proto"];
592
+ const proto = protoHeader ?? (req.secure ? "https" : "http");
593
+ const host = req.get("host") ?? "localhost";
594
+ const url = `${proto}://${host}${req.originalUrl}`;
595
+ return { headers, rawBody, url };
596
+ }
597
+ async function createWebhookServer(opts) {
598
+ const expressMod = await loadExpress();
599
+ const app = opts.app ?? expressMod.default();
600
+ const prefix = opts.path ?? "/sms";
601
+ const backend = opts.adapter.getBackendKind();
602
+ const rawCapture = (req, _res, next) => {
603
+ let buf = "";
604
+ req.setEncoding("utf8");
605
+ req.on("data", (chunk) => {
606
+ buf += chunk;
607
+ });
608
+ req.on("end", () => {
609
+ req.rawBody = buf;
610
+ next();
611
+ });
612
+ req.on("error", (err) => next(err));
613
+ };
614
+ const handler = (req, res) => {
615
+ const ctx = buildSignatureContext(req);
616
+ if (!opts.adapter.verifySignature(ctx)) {
617
+ res.status(401).type("text/plain").send("invalid signature");
618
+ return;
619
+ }
620
+ let event;
621
+ try {
622
+ event = opts.adapter.buildEventFromCtx(ctx);
623
+ } catch (err) {
624
+ const msg = err instanceof Error ? err.message : String(err);
625
+ res.status(400).type("text/plain").send(`parse failed: ${msg}`);
626
+ return;
627
+ }
628
+ void opts.adapter.dispatchEvent(event);
629
+ res.status(204).end();
630
+ };
631
+ app.post(`${prefix}/${backend}`, rawCapture, handler);
632
+ let server;
633
+ let started = false;
634
+ let stopped = false;
635
+ return {
636
+ async start() {
637
+ if (started || opts.app !== void 0) {
638
+ started = true;
639
+ return;
640
+ }
641
+ const port = opts.port ?? 3e3;
642
+ await new Promise((resolve) => {
643
+ server = app.listen(port, () => resolve());
644
+ });
645
+ started = true;
646
+ },
647
+ async stop() {
648
+ if (stopped) return;
649
+ stopped = true;
650
+ if (server === void 0) return;
651
+ await new Promise((resolve) => {
652
+ server?.close(() => resolve());
653
+ });
654
+ server = void 0;
655
+ }
656
+ };
657
+ }
658
+
659
+ export { BackendNotInstalledError, ConfigurationError, SMSAdapter, createWebhookServer, normalizeE164, splitForSMS };
660
+ //# sourceMappingURL=index.js.map
661
+ //# sourceMappingURL=index.js.map