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