@terreno/comms 57.2.0 → 57.3.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.
Files changed (57) hide show
  1. package/README.md +58 -0
  2. package/dist/adapters/expoPush.d.ts +54 -0
  3. package/dist/adapters/expoPush.js +400 -0
  4. package/dist/adapters/sendgrid.d.ts +3 -0
  5. package/dist/adapters/sendgrid.js +7 -1
  6. package/dist/adapters/twilioSms.d.ts +36 -0
  7. package/dist/adapters/twilioSms.js +232 -0
  8. package/dist/adapters/twilioVerify.d.ts +44 -0
  9. package/dist/adapters/twilioVerify.js +212 -0
  10. package/dist/commsApp.d.ts +4 -1
  11. package/dist/commsApp.js +28 -2
  12. package/dist/commsQuery.d.ts +30 -0
  13. package/dist/commsQuery.js +134 -0
  14. package/dist/commsRetry.d.ts +16 -0
  15. package/dist/commsRetry.js +79 -0
  16. package/dist/commsService.d.ts +11 -4
  17. package/dist/commsService.js +217 -47
  18. package/dist/index.d.ts +3 -3
  19. package/dist/index.js +3 -1
  20. package/dist/routes/commsDashboard.d.ts +11 -0
  21. package/dist/routes/commsDashboard.js +414 -0
  22. package/dist/templates.d.ts +9 -0
  23. package/dist/templates.js +34 -1
  24. package/dist/types.d.ts +11 -0
  25. package/dist/webhooks/sendgridWebhooks.d.ts +16 -0
  26. package/dist/webhooks/sendgridWebhooks.js +251 -0
  27. package/dist/webhooks/twilioWebhooks.d.ts +18 -0
  28. package/dist/webhooks/twilioWebhooks.js +175 -0
  29. package/package.json +26 -5
  30. package/src/adapters/expoPush.test.ts +585 -0
  31. package/src/adapters/expoPush.ts +304 -0
  32. package/src/adapters/sendgrid.ts +8 -0
  33. package/src/adapters/twilioSms.test.ts +374 -0
  34. package/src/adapters/twilioSms.ts +237 -0
  35. package/src/adapters/twilioVerify.test.ts +207 -0
  36. package/src/adapters/twilioVerify.ts +227 -0
  37. package/src/commsApp.test.ts +13 -0
  38. package/src/commsApp.ts +38 -3
  39. package/src/commsQuery.test.ts +165 -0
  40. package/src/commsQuery.ts +162 -0
  41. package/src/commsRetry.ts +87 -0
  42. package/src/commsService.test.ts +68 -0
  43. package/src/commsService.ts +177 -20
  44. package/src/index.ts +9 -2
  45. package/src/routes/commsDashboard.test.ts +310 -0
  46. package/src/routes/commsDashboard.ts +327 -0
  47. package/src/templates.test.ts +63 -1
  48. package/src/templates.ts +47 -0
  49. package/src/tests/bunSetup.ts +8 -0
  50. package/src/types.ts +13 -0
  51. package/src/webhooks/sendgridWebhooks.test.ts +520 -0
  52. package/src/webhooks/sendgridWebhooks.ts +166 -0
  53. package/src/webhooks/twilioWebhooks.test.ts +352 -0
  54. package/src/webhooks/twilioWebhooks.ts +154 -0
  55. package/dist/routes/commsExplorer.d.ts +0 -7
  56. package/dist/routes/commsExplorer.js +0 -147
  57. package/src/routes/commsExplorer.ts +0 -114
@@ -0,0 +1,166 @@
1
+ import {logger, sendgridEventSignature, type WebhooksApp} from "@terreno/api";
2
+
3
+ import {SendGridMailProvider} from "../adapters/sendgrid";
4
+ import type {CommsService} from "../commsService";
5
+ import {CommsMessage} from "../models/commsMessage";
6
+ import type {OptOutEvent} from "../types";
7
+
8
+ const eventString = (value: unknown): string => {
9
+ return typeof value === "string" ? value : "";
10
+ };
11
+
12
+ const escapeRegex = (value: string): string => {
13
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14
+ };
15
+
16
+ const storedProviderMessageId = async (sgMessageId: string): Promise<string> => {
17
+ const prefix = sgMessageId.split(".")[0] ?? sgMessageId;
18
+ if (!prefix) {
19
+ return sgMessageId;
20
+ }
21
+ const exact = await CommsMessage.findOneOrNone({providerMessageId: prefix});
22
+ if (exact?.providerMessageId) {
23
+ return exact.providerMessageId;
24
+ }
25
+ const prefixed = await CommsMessage.findOneOrNone({
26
+ providerMessageId: new RegExp(`^${escapeRegex(prefix)}`),
27
+ });
28
+ return prefixed?.providerMessageId ?? prefix;
29
+ };
30
+
31
+ const applySendGridEvent = async ({
32
+ event,
33
+ service,
34
+ }: {
35
+ event: Record<string, unknown>;
36
+ service: CommsService;
37
+ }): Promise<void> => {
38
+ const type = eventString(event.event);
39
+ const providerMessageId = await storedProviderMessageId(eventString(event.sg_message_id));
40
+ const reason = eventString(event.reason);
41
+ const email = eventString(event.email);
42
+
43
+ if (type === "delivered") {
44
+ await service.recordDeliveryEvent({
45
+ channel: "mail",
46
+ providerMessageId,
47
+ raw: event,
48
+ status: "delivered",
49
+ });
50
+ return;
51
+ }
52
+ if (type === "open") {
53
+ await service.recordDeliveryEvent({
54
+ channel: "mail",
55
+ providerMessageId,
56
+ raw: event,
57
+ status: "opened",
58
+ });
59
+ return;
60
+ }
61
+ if (type === "bounce") {
62
+ const isSoft = eventString(event.type) === "blocked";
63
+ await service.recordDeliveryEvent({
64
+ channel: "mail",
65
+ errorClass: isSoft ? "transient" : "permanent",
66
+ errorCode: reason || (isSoft ? "deferred" : "bounce"),
67
+ providerMessageId,
68
+ raw: event,
69
+ status: "bounced",
70
+ });
71
+ return;
72
+ }
73
+ if (type === "dropped") {
74
+ await service.recordDeliveryEvent({
75
+ channel: "mail",
76
+ errorClass: "permanent",
77
+ errorCode: reason || "dropped",
78
+ providerMessageId,
79
+ raw: event,
80
+ status: "failed",
81
+ });
82
+ return;
83
+ }
84
+ if (type === "spamreport" || type === "unsubscribe" || type === "group_unsubscribe") {
85
+ const optOut: OptOutEvent = {
86
+ channel: "mail",
87
+ provider: "sendgrid",
88
+ raw: event,
89
+ reason: type,
90
+ to: email,
91
+ };
92
+ await service.recordOptOut(optOut);
93
+ }
94
+ };
95
+
96
+ export const registerSendGridCommsWebhooks = ({
97
+ basePath,
98
+ publicKey,
99
+ service,
100
+ webhooks,
101
+ }: {
102
+ basePath: string;
103
+ publicKey: string;
104
+ service: CommsService;
105
+ webhooks: WebhooksApp;
106
+ }): void => {
107
+ webhooks.route({
108
+ handler: async ({body}): Promise<void> => {
109
+ if (!Array.isArray(body)) {
110
+ return;
111
+ }
112
+ for (const item of body) {
113
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
114
+ continue;
115
+ }
116
+ const event = item as Record<string, unknown>;
117
+ const eventId = eventString(event.sg_event_id);
118
+ if (!eventId) {
119
+ continue;
120
+ }
121
+ const claimResult = await webhooks.claim({eventId, source: "sendgrid"});
122
+ if (claimResult === "duplicate") {
123
+ continue;
124
+ }
125
+ try {
126
+ await applySendGridEvent({event, service});
127
+ } catch (error) {
128
+ await webhooks.release({eventId, source: "sendgrid"});
129
+ throw error;
130
+ }
131
+ }
132
+ },
133
+ path: `${basePath}/webhooks/sendgrid`,
134
+ source: "sendgrid",
135
+ verify: sendgridEventSignature({publicKey}),
136
+ });
137
+ };
138
+
139
+ export const maybeRegisterSendGridCommsWebhooks = ({
140
+ basePath,
141
+ mail,
142
+ service,
143
+ webhooks,
144
+ }: {
145
+ basePath: string;
146
+ mail?: {id: string};
147
+ service: CommsService;
148
+ webhooks?: WebhooksApp;
149
+ }): void => {
150
+ if (!webhooks || !(mail instanceof SendGridMailProvider)) {
151
+ return;
152
+ }
153
+ const publicKey = mail.getWebhookVerificationKey();
154
+ if (!publicKey) {
155
+ logger.error(
156
+ "[comms] Skipping SendGrid webhook routes; set webhookVerificationKey or SENDGRID_WEBHOOK_VERIFICATION_KEY"
157
+ );
158
+ return;
159
+ }
160
+ registerSendGridCommsWebhooks({
161
+ basePath,
162
+ publicKey,
163
+ service,
164
+ webhooks,
165
+ });
166
+ };
@@ -0,0 +1,352 @@
1
+ import {beforeEach, describe, it, spyOn} from "bun:test";
2
+ import crypto from "node:crypto";
3
+ import {logger, TerrenoApp, type UserModel as UserModelType, WebhooksApp} from "@terreno/api";
4
+ import {setupDb, UserModel} from "@terreno/api/testing";
5
+ import {assert} from "chai";
6
+ import type {Application} from "express";
7
+ import supertest from "supertest";
8
+
9
+ import {type TwilioSmsClient, TwilioSmsProvider} from "../adapters/twilioSms";
10
+ import {CommsApp} from "../commsApp";
11
+ import {CommsMessage} from "../models/commsMessage";
12
+ import type {OptOutEvent} from "../types";
13
+
14
+ const AUTH_TOKEN = "twilio-auth-token";
15
+ const PUBLIC_URL = "https://api.example.test";
16
+ const STATUS_PATH = "/comms/webhooks/twilio/status";
17
+ const INBOUND_PATH = "/comms/webhooks/twilio/inbound";
18
+ const STATUS_URL = `${PUBLIC_URL}${STATUS_PATH}`;
19
+ const INBOUND_URL = `${PUBLIC_URL}${INBOUND_PATH}`;
20
+ const MESSAGE_SID = "SM123delivered";
21
+ const FAILED_SID = "SM123failed";
22
+
23
+ const createMockClient = (
24
+ sid: string
25
+ ): TwilioSmsClient & {calls: {params: {statusCallback?: string}}[]} => {
26
+ const calls: {params: {statusCallback?: string}}[] = [];
27
+ return {
28
+ calls,
29
+ messages: {
30
+ create: async (params): Promise<{sid: string}> => {
31
+ calls.push({params});
32
+ return {sid};
33
+ },
34
+ },
35
+ };
36
+ };
37
+
38
+ const twilioSignatureHeader = ({
39
+ fields,
40
+ url,
41
+ }: {
42
+ fields: Record<string, string>;
43
+ url: string;
44
+ }): string => {
45
+ const keys = Object.keys(fields).sort();
46
+ let data = url;
47
+ for (const key of keys) {
48
+ data += key + fields[key];
49
+ }
50
+ return crypto.createHmac("sha1", AUTH_TOKEN).update(data, "utf8").digest("base64");
51
+ };
52
+
53
+ const postTwilioForm = ({
54
+ app,
55
+ fields,
56
+ path,
57
+ signature,
58
+ url,
59
+ }: {
60
+ app: Application;
61
+ fields: Record<string, string>;
62
+ path: string;
63
+ signature?: string;
64
+ url: string;
65
+ }): Promise<supertest.Response> => {
66
+ const request = supertest(app).post(path).type("form");
67
+ if (signature !== undefined) {
68
+ request.set("X-Twilio-Signature", signature);
69
+ } else {
70
+ request.set("X-Twilio-Signature", twilioSignatureHeader({fields, url}));
71
+ }
72
+ return request.send(fields);
73
+ };
74
+
75
+ const buildTwilioCommsApp = ({
76
+ client,
77
+ onOptOut,
78
+ webhookPublicUrl = PUBLIC_URL,
79
+ webhooks = new WebhooksApp({idempotency: {store: "memory"}}),
80
+ }: {
81
+ client: TwilioSmsClient;
82
+ onOptOut?: (event: OptOutEvent) => Promise<void>;
83
+ webhookPublicUrl?: string;
84
+ webhooks?: WebhooksApp;
85
+ }): {
86
+ app: Application;
87
+ comms: CommsApp;
88
+ sms: TwilioSmsProvider;
89
+ webhooks: WebhooksApp;
90
+ } => {
91
+ const sms = new TwilioSmsProvider({
92
+ accountSid: "ACtest",
93
+ authToken: AUTH_TOKEN,
94
+ client,
95
+ fromNumber: "+15555550199",
96
+ });
97
+ const comms = new CommsApp({
98
+ onOptOut,
99
+ sms,
100
+ webhookPublicUrl,
101
+ webhooks,
102
+ });
103
+ const app = new TerrenoApp({
104
+ logRequests: false,
105
+ skipListen: true,
106
+ userModel: UserModel as unknown as UserModelType,
107
+ })
108
+ .register(comms)
109
+ .register(webhooks)
110
+ .build();
111
+ return {app, comms, sms, webhooks};
112
+ };
113
+
114
+ describe("Twilio CommsApp webhooks", () => {
115
+ beforeEach(async (): Promise<void> => {
116
+ await setupDb();
117
+ await CommsMessage.deleteMany({});
118
+ Reflect.deleteProperty(process.env, "PUBLIC_API_URL");
119
+ Reflect.deleteProperty(process.env, "COMMS_WEBHOOK_PUBLIC_URL");
120
+ });
121
+
122
+ it("updates CommsMessage to delivered from a signed status callback", async (): Promise<void> => {
123
+ const client = createMockClient(MESSAGE_SID);
124
+ const {app, comms} = buildTwilioCommsApp({client});
125
+ await comms.service.sendSms({body: "Hello", to: "+14155552671"});
126
+
127
+ const fields = {MessageSid: MESSAGE_SID, MessageStatus: "delivered"};
128
+ const res = await postTwilioForm({app, fields, path: STATUS_PATH, url: STATUS_URL});
129
+
130
+ assert.equal(res.status, 200);
131
+ assert.equal(res.body.received, true);
132
+ const row = await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_SID});
133
+ assert.equal(row.status, "delivered");
134
+ });
135
+
136
+ it("maps failed + ErrorCode 21610 to permanent failed", async (): Promise<void> => {
137
+ const client = createMockClient(FAILED_SID);
138
+ const {app, comms} = buildTwilioCommsApp({client});
139
+ await comms.service.sendSms({body: "Hello", to: "+14155552671"});
140
+
141
+ const fields = {
142
+ ErrorCode: "21610",
143
+ MessageSid: FAILED_SID,
144
+ MessageStatus: "failed",
145
+ };
146
+ const res = await postTwilioForm({app, fields, path: STATUS_PATH, url: STATUS_URL});
147
+
148
+ assert.equal(res.status, 200);
149
+ const row = await CommsMessage.findExactlyOne({providerMessageId: FAILED_SID});
150
+ assert.equal(row.status, "failed");
151
+ assert.equal(row.errorCode, "21610");
152
+ assert.equal(row.errorClass, "permanent");
153
+ });
154
+
155
+ it("returns 401 webhook-signature-invalid for an unsigned status callback", async (): Promise<void> => {
156
+ const client = createMockClient(MESSAGE_SID);
157
+ const {app} = buildTwilioCommsApp({client});
158
+ const res = await postTwilioForm({
159
+ app,
160
+ fields: {MessageSid: MESSAGE_SID, MessageStatus: "delivered"},
161
+ path: STATUS_PATH,
162
+ signature: "",
163
+ url: STATUS_URL,
164
+ });
165
+
166
+ assert.equal(res.status, 401);
167
+ assert.equal(res.body.code, "webhook-signature-invalid");
168
+ });
169
+
170
+ it("fires onOptOut with reason sms-stop for a signed STOP inbound", async (): Promise<void> => {
171
+ const client = createMockClient("SMinbound");
172
+ const optOuts: OptOutEvent[] = [];
173
+ const {app} = buildTwilioCommsApp({
174
+ client,
175
+ onOptOut: async (event): Promise<void> => {
176
+ optOuts.push(event);
177
+ },
178
+ });
179
+ const fields = {
180
+ Body: "STOP please",
181
+ From: "+14155552671",
182
+ MessageSid: "SMinbound",
183
+ };
184
+ const res = await postTwilioForm({
185
+ app,
186
+ fields,
187
+ path: INBOUND_PATH,
188
+ url: INBOUND_URL,
189
+ });
190
+
191
+ assert.equal(res.status, 200);
192
+ assert.equal(optOuts.length, 1);
193
+ assert.equal(optOuts[0]?.reason, "sms-stop");
194
+ assert.equal(optOuts[0]?.channel, "sms");
195
+ assert.equal(optOuts[0]?.to, "+14155552671");
196
+ });
197
+
198
+ it("does not mount Twilio webhook paths when webhooks is omitted", async (): Promise<void> => {
199
+ const sms = new TwilioSmsProvider({
200
+ accountSid: "ACtest",
201
+ authToken: AUTH_TOKEN,
202
+ client: createMockClient("SM404"),
203
+ fromNumber: "+15555550199",
204
+ });
205
+ const app = new TerrenoApp({
206
+ logRequests: false,
207
+ skipListen: true,
208
+ userModel: UserModel as unknown as UserModelType,
209
+ })
210
+ .register(
211
+ new CommsApp({
212
+ sms,
213
+ webhookPublicUrl: PUBLIC_URL,
214
+ })
215
+ )
216
+ .build();
217
+
218
+ const res = await supertest(app)
219
+ .post(STATUS_PATH)
220
+ .type("form")
221
+ .send({MessageSid: "SM404", MessageStatus: "delivered"});
222
+
223
+ assert.equal(res.status, 404);
224
+ });
225
+
226
+ it("skips Twilio routes and logs when the public URL is missing", async (): Promise<void> => {
227
+ const errorSpy = spyOn(logger, "error");
228
+ const webhooks = new WebhooksApp({idempotency: {store: "memory"}});
229
+ const sms = new TwilioSmsProvider({
230
+ accountSid: "ACtest",
231
+ authToken: AUTH_TOKEN,
232
+ client: createMockClient("SMskip"),
233
+ fromNumber: "+15555550199",
234
+ });
235
+ const app = new TerrenoApp({
236
+ logRequests: false,
237
+ skipListen: true,
238
+ userModel: UserModel as unknown as UserModelType,
239
+ })
240
+ .register(new CommsApp({sms, webhooks}))
241
+ .register(webhooks)
242
+ .build();
243
+
244
+ const res = await supertest(app)
245
+ .post(STATUS_PATH)
246
+ .type("form")
247
+ .send({MessageSid: "SMskip", MessageStatus: "delivered"});
248
+
249
+ assert.equal(res.status, 404);
250
+ assert.isTrue(
251
+ errorSpy.mock.calls.some((call) => String(call[0]).includes("Skipping Twilio webhook routes"))
252
+ );
253
+ errorSpy.mockRestore();
254
+ });
255
+
256
+ it("defaults statusCallbackUrl to the public Twilio status path", async (): Promise<void> => {
257
+ const client = createMockClient("SMcallback");
258
+ const {comms} = buildTwilioCommsApp({client});
259
+ await comms.service.sendSms({body: "Hello", to: "+14155552671"});
260
+ assert.equal(client.calls[0]?.params.statusCallback, STATUS_URL);
261
+ });
262
+
263
+ it("does not change CommsMessage for queued, accepted, sending, or sent", async (): Promise<void> => {
264
+ const sid = "SMnoop";
265
+ const client = createMockClient(sid);
266
+ const {app, comms} = buildTwilioCommsApp({client});
267
+ await comms.service.sendSms({body: "Hello", to: "+14155552671"});
268
+ for (const messageStatus of ["queued", "accepted", "sending", "sent"]) {
269
+ const res = await postTwilioForm({
270
+ app,
271
+ fields: {MessageSid: sid, MessageStatus: messageStatus},
272
+ path: STATUS_PATH,
273
+ url: STATUS_URL,
274
+ });
275
+ assert.equal(res.status, 200);
276
+ }
277
+ const row = await CommsMessage.findExactlyOne({providerMessageId: sid});
278
+ assert.equal(row.status, "sent");
279
+ });
280
+
281
+ it("maps undelivered with a non-21610 ErrorCode to transient failed", async (): Promise<void> => {
282
+ const sid = "SMundelivered";
283
+ const client = createMockClient(sid);
284
+ const {app, comms} = buildTwilioCommsApp({client});
285
+ await comms.service.sendSms({body: "Hello", to: "+14155552671"});
286
+ const res = await postTwilioForm({
287
+ app,
288
+ fields: {ErrorCode: "30001", MessageSid: sid, MessageStatus: "undelivered"},
289
+ path: STATUS_PATH,
290
+ url: STATUS_URL,
291
+ });
292
+ assert.equal(res.status, 200);
293
+ const row = await CommsMessage.findExactlyOne({providerMessageId: sid});
294
+ assert.equal(row.status, "failed");
295
+ assert.equal(row.errorCode, "30001");
296
+ assert.equal(row.errorClass, "transient");
297
+ });
298
+
299
+ it("fires onOptOut with reason sms-start for a signed START inbound", async (): Promise<void> => {
300
+ const optOuts: OptOutEvent[] = [];
301
+ const {app} = buildTwilioCommsApp({
302
+ client: createMockClient("SMstart"),
303
+ onOptOut: async (event): Promise<void> => {
304
+ optOuts.push(event);
305
+ },
306
+ });
307
+ const res = await postTwilioForm({
308
+ app,
309
+ fields: {Body: "START", From: "+14155552671", MessageSid: "SMstart"},
310
+ path: INBOUND_PATH,
311
+ url: INBOUND_URL,
312
+ });
313
+ assert.equal(res.status, 200);
314
+ assert.equal(optOuts[0]?.reason, "sms-start");
315
+ });
316
+
317
+ it("skips Twilio routes and logs when the auth token is missing", async (): Promise<void> => {
318
+ const errorSpy = spyOn(logger, "error");
319
+ const webhooks = new WebhooksApp({idempotency: {store: "memory"}});
320
+ const sms = new TwilioSmsProvider({
321
+ accountSid: "ACtest",
322
+ authToken: AUTH_TOKEN,
323
+ client: createMockClient("SMnotoken"),
324
+ fromNumber: "+15555550199",
325
+ });
326
+ sms.getAuthToken = (): string => "";
327
+ const app = new TerrenoApp({
328
+ logRequests: false,
329
+ skipListen: true,
330
+ userModel: UserModel as unknown as UserModelType,
331
+ })
332
+ .register(new CommsApp({sms, webhookPublicUrl: PUBLIC_URL, webhooks}))
333
+ .register(webhooks)
334
+ .build();
335
+ const res = await supertest(app)
336
+ .post(STATUS_PATH)
337
+ .type("form")
338
+ .send({MessageSid: "SMnotoken", MessageStatus: "delivered"});
339
+ assert.equal(res.status, 404);
340
+ assert.isTrue(
341
+ errorSpy.mock.calls.some((call) => String(call[0]).includes("auth token is missing"))
342
+ );
343
+ errorSpy.mockRestore();
344
+ });
345
+
346
+ it("omits Twilio webhook paths from OpenAPI", async (): Promise<void> => {
347
+ const {app} = buildTwilioCommsApp({client: createMockClient("SMopenapi")});
348
+ const response = await supertest(app).get("/openapi.json").expect(200);
349
+ assert.notProperty(response.body.paths, STATUS_PATH);
350
+ assert.notProperty(response.body.paths, INBOUND_PATH);
351
+ });
352
+ });
@@ -0,0 +1,154 @@
1
+ import {logger, twilioSignature, type WebhooksApp} from "@terreno/api";
2
+ import type {Request} from "express";
3
+
4
+ import {TwilioSmsProvider} from "../adapters/twilioSms";
5
+ import type {CommsService} from "../commsService";
6
+ import type {DeliveryEvent} from "../types";
7
+
8
+ const formString = (body: unknown, key: string): string => {
9
+ if (!body || typeof body !== "object") {
10
+ return "";
11
+ }
12
+ const value = (body as Record<string, unknown>)[key];
13
+ return typeof value === "string" ? value : "";
14
+ };
15
+
16
+ const inboundKeyword = (body: string): "sms-start" | "sms-stop" | undefined => {
17
+ const keyword = body.trim().split(/\s+/)[0]?.toUpperCase();
18
+ if (keyword === "STOP") {
19
+ return "sms-stop";
20
+ }
21
+ if (keyword === "START") {
22
+ return "sms-start";
23
+ }
24
+ return undefined;
25
+ };
26
+
27
+ const mapStatus = (
28
+ messageStatus: string,
29
+ errorCode: string
30
+ ): Pick<DeliveryEvent, "errorClass" | "errorCode" | "status"> | undefined => {
31
+ if (messageStatus === "delivered") {
32
+ return {status: "delivered"};
33
+ }
34
+ if (messageStatus === "undelivered" || messageStatus === "failed") {
35
+ return {
36
+ errorClass: errorCode === "21610" ? "permanent" : "transient",
37
+ errorCode: errorCode || undefined,
38
+ status: "failed",
39
+ };
40
+ }
41
+ return undefined;
42
+ };
43
+
44
+ export const registerTwilioCommsWebhooks = ({
45
+ authToken,
46
+ basePath,
47
+ publicUrl,
48
+ service,
49
+ webhooks,
50
+ }: {
51
+ authToken: string;
52
+ basePath: string;
53
+ publicUrl: string;
54
+ service: CommsService;
55
+ webhooks: WebhooksApp;
56
+ }): void => {
57
+ const statusPath = `${basePath}/webhooks/twilio/status`;
58
+ const inboundPath = `${basePath}/webhooks/twilio/inbound`;
59
+ const statusUrl = `${publicUrl}${statusPath}`;
60
+ const inboundUrl = `${publicUrl}${inboundPath}`;
61
+
62
+ webhooks.route({
63
+ eventId: (req: Request): string => {
64
+ const sid = formString(req.body, "MessageSid");
65
+ const status = formString(req.body, "MessageStatus");
66
+ return status ? `${sid}:${status}` : sid;
67
+ },
68
+ handler: async ({body}): Promise<void> => {
69
+ const messageStatus = formString(body, "MessageStatus");
70
+ const mapped = mapStatus(messageStatus, formString(body, "ErrorCode"));
71
+ if (!mapped) {
72
+ return;
73
+ }
74
+ await service.recordDeliveryEvent({
75
+ channel: "sms",
76
+ errorClass: mapped.errorClass,
77
+ errorCode: mapped.errorCode,
78
+ providerMessageId: formString(body, "MessageSid"),
79
+ raw: body,
80
+ status: mapped.status,
81
+ });
82
+ },
83
+ path: statusPath,
84
+ source: "twilio-status",
85
+ verify: twilioSignature({authToken, url: statusUrl}),
86
+ });
87
+
88
+ webhooks.route({
89
+ eventId: (req: Request): string => {
90
+ const sid = formString(req.body, "SmsSid") || formString(req.body, "MessageSid");
91
+ const keyword = inboundKeyword(formString(req.body, "Body")) ?? "inbound";
92
+ return `${sid}:${keyword}`;
93
+ },
94
+ handler: async ({body}): Promise<void> => {
95
+ const reason = inboundKeyword(formString(body, "Body"));
96
+ if (!reason) {
97
+ return;
98
+ }
99
+ await service.recordOptOut({
100
+ channel: "sms",
101
+ provider: "twilio",
102
+ raw: body,
103
+ reason,
104
+ to: formString(body, "From"),
105
+ });
106
+ },
107
+ path: inboundPath,
108
+ source: "twilio-inbound",
109
+ verify: twilioSignature({authToken, url: inboundUrl}),
110
+ });
111
+ };
112
+
113
+ export const maybeRegisterTwilioCommsWebhooks = ({
114
+ basePath,
115
+ publicUrl,
116
+ service,
117
+ sms,
118
+ webhooks,
119
+ }: {
120
+ basePath: string;
121
+ publicUrl?: string;
122
+ service: CommsService;
123
+ sms?: {id: string};
124
+ webhooks?: WebhooksApp;
125
+ }): void => {
126
+ if (!webhooks || !(sms instanceof TwilioSmsProvider)) {
127
+ return;
128
+ }
129
+ const authToken = sms.getAuthToken();
130
+ if (!authToken) {
131
+ logger.error("[comms] Skipping Twilio webhook routes; auth token is missing");
132
+ return;
133
+ }
134
+ const resolvedPublicUrl = (
135
+ publicUrl ??
136
+ process.env.PUBLIC_API_URL ??
137
+ process.env.COMMS_WEBHOOK_PUBLIC_URL ??
138
+ ""
139
+ ).replace(/\/$/, "");
140
+ if (!resolvedPublicUrl) {
141
+ logger.error(
142
+ "[comms] Skipping Twilio webhook routes; set webhookPublicUrl, PUBLIC_API_URL, or COMMS_WEBHOOK_PUBLIC_URL"
143
+ );
144
+ return;
145
+ }
146
+ sms.applyDefaultStatusCallbackUrl(`${resolvedPublicUrl}${basePath}/webhooks/twilio/status`);
147
+ registerTwilioCommsWebhooks({
148
+ authToken,
149
+ basePath,
150
+ publicUrl: resolvedPublicUrl,
151
+ service,
152
+ webhooks,
153
+ });
154
+ };
@@ -1,7 +0,0 @@
1
- import type express from "express";
2
- interface CommsExplorerRouteOptions {
3
- path?: string;
4
- openApi?: unknown;
5
- }
6
- export declare const addCommsExplorerRoute: (app: express.Application, options?: CommsExplorerRouteOptions) => void;
7
- export {};