@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
@@ -1,7 +1,7 @@
1
1
  import {describe, it} from "bun:test";
2
2
  import {assert} from "chai";
3
3
 
4
- import {renderTemplate} from "./templates";
4
+ import {renderAuthMail, renderTemplate} from "./templates";
5
5
 
6
6
  describe("renderTemplate", () => {
7
7
  it("interpolates own data fields across subject, text, and html", (): void => {
@@ -34,4 +34,66 @@ describe("renderTemplate", () => {
34
34
 
35
35
  assert.equal(rendered.subject, " Ada");
36
36
  });
37
+
38
+ it("renders empty strings for null and undefined own properties", (): void => {
39
+ const rendered = renderTemplate({
40
+ data: {name: null, title: undefined},
41
+ template: {
42
+ html: "<p>{{name}}</p>",
43
+ subject: "{{title}} {{name}}",
44
+ text: "{{name}}",
45
+ },
46
+ });
47
+ assert.deepEqual(rendered, {
48
+ html: "<p></p>",
49
+ subject: " ",
50
+ text: "",
51
+ });
52
+ });
53
+ });
54
+
55
+ describe("auth mail templates", () => {
56
+ it("renders resetPassword and verifyEmail links from publicAppUrl", (): void => {
57
+ const reset = renderAuthMail({
58
+ publicAppUrl: "https://app.example.com/",
59
+ templateId: "resetPassword",
60
+ token: "abc123",
61
+ });
62
+ const verify = renderAuthMail({
63
+ publicAppUrl: "https://app.example.com/",
64
+ templateId: "verifyEmail",
65
+ token: "def456",
66
+ });
67
+
68
+ assert.deepEqual(reset, {
69
+ html: '<p><a href="https://app.example.com/resetPassword?token=abc123">Reset your password</a></p>',
70
+ subject: "Reset your password",
71
+ text: "Reset your password using this link: https://app.example.com/resetPassword?token=abc123",
72
+ });
73
+ assert.deepEqual(verify, {
74
+ html: '<p><a href="https://app.example.com/verifyEmail?token=def456">Verify your email</a></p>',
75
+ subject: "Verify your email",
76
+ text: "Verify your email using this link: https://app.example.com/verifyEmail?token=def456",
77
+ });
78
+ });
79
+
80
+ it("uses app-provided template overrides when present", (): void => {
81
+ const rendered = renderAuthMail({
82
+ publicAppUrl: "https://app.example.com",
83
+ templateId: "resetPassword",
84
+ templates: {
85
+ resetPassword: {
86
+ html: "<p>{{resetUrl}}</p>",
87
+ subject: "Reset for {{token}}",
88
+ text: "{{resetUrl}}",
89
+ },
90
+ },
91
+ token: "abc123",
92
+ });
93
+ assert.deepEqual(rendered, {
94
+ html: "<p>https://app.example.com/resetPassword?token=abc123</p>",
95
+ subject: "Reset for abc123",
96
+ text: "https://app.example.com/resetPassword?token=abc123",
97
+ });
98
+ });
37
99
  });
package/src/templates.ts CHANGED
@@ -9,6 +9,28 @@ export interface RenderTemplateOptions {
9
9
  template: MessageTemplate;
10
10
  }
11
11
 
12
+ export type AuthMailTemplateId = "resetPassword" | "verifyEmail";
13
+
14
+ export interface RenderAuthMailOptions {
15
+ publicAppUrl: string;
16
+ templateId: AuthMailTemplateId;
17
+ token: string;
18
+ templates?: Partial<Record<AuthMailTemplateId, MessageTemplate>>;
19
+ }
20
+
21
+ export const DEFAULT_AUTH_MAIL_TEMPLATES: Record<AuthMailTemplateId, MessageTemplate> = {
22
+ resetPassword: {
23
+ html: '<p><a href="{{resetUrl}}">Reset your password</a></p>',
24
+ subject: "Reset your password",
25
+ text: "Reset your password using this link: {{resetUrl}}",
26
+ },
27
+ verifyEmail: {
28
+ html: '<p><a href="{{verifyUrl}}">Verify your email</a></p>',
29
+ subject: "Verify your email",
30
+ text: "Verify your email using this link: {{verifyUrl}}",
31
+ },
32
+ };
33
+
12
34
  const TEMPLATE_VARIABLE_PATTERN = /{{\s*([A-Za-z0-9_]+)\s*}}/g;
13
35
 
14
36
  const interpolate = (value: string, data: Record<string, unknown>): string =>
@@ -29,3 +51,28 @@ export const renderTemplate = ({data, template}: RenderTemplateOptions): Message
29
51
  subject: interpolate(template.subject, data),
30
52
  ...(template.text === undefined ? {} : {text: interpolate(template.text, data)}),
31
53
  });
54
+
55
+ const authMailUrl = (publicAppUrl: string, path: string, token: string): string => {
56
+ const base = publicAppUrl.replace(/\/$/, "");
57
+ return `${base}${path}?token=${encodeURIComponent(token)}`;
58
+ };
59
+
60
+ export const renderAuthMail = ({
61
+ publicAppUrl,
62
+ templateId,
63
+ token,
64
+ templates,
65
+ }: RenderAuthMailOptions): MessageTemplate => {
66
+ const template = templates?.[templateId] ?? DEFAULT_AUTH_MAIL_TEMPLATES[templateId];
67
+ const resetUrl = authMailUrl(publicAppUrl, "/resetPassword", token);
68
+ const verifyUrl = authMailUrl(publicAppUrl, "/verifyEmail", token);
69
+ return renderTemplate({
70
+ data: {
71
+ publicAppUrl: publicAppUrl.replace(/\/$/, ""),
72
+ resetUrl,
73
+ token,
74
+ verifyUrl,
75
+ },
76
+ template,
77
+ });
78
+ };
@@ -12,4 +12,12 @@ registerSimpleMongoPreload({
12
12
  beforeEach((): void => {
13
13
  process.env.NODE_ENV = "test";
14
14
  Reflect.deleteProperty(process.env, "SENDGRID_API_KEY");
15
+ Reflect.deleteProperty(process.env, "TWILIO_ACCOUNT_SID");
16
+ Reflect.deleteProperty(process.env, "TWILIO_AUTH_TOKEN");
17
+ Reflect.deleteProperty(process.env, "TWILIO_FROM_NUMBER");
18
+ Reflect.deleteProperty(process.env, "TWILIO_MESSAGING_SERVICE_SID");
19
+ Reflect.deleteProperty(process.env, "TWILIO_VERIFY_SERVICE_SID");
20
+ Reflect.deleteProperty(process.env, "PUBLIC_API_URL");
21
+ Reflect.deleteProperty(process.env, "COMMS_WEBHOOK_PUBLIC_URL");
22
+ Reflect.deleteProperty(process.env, "SENDGRID_WEBHOOK_VERIFICATION_KEY");
15
23
  });
package/src/types.ts CHANGED
@@ -8,6 +8,8 @@ export interface SendResult {
8
8
  errorClass?: CommsErrorClass;
9
9
  errorCode?: string;
10
10
  isPermanentFailure?: boolean;
11
+ /** Id of the CommsMessage row written for this send, when logging is on. */
12
+ loggedMessageId?: string;
11
13
  metadata?: Record<string, unknown>;
12
14
  providerMessageId?: string;
13
15
  }
@@ -129,6 +131,17 @@ export interface CommsOptions {
129
131
  verification?: VerificationProvider;
130
132
  }
131
133
 
134
+ export interface CommsSendOptions {
135
+ extraMetadata?: Record<string, unknown>;
136
+ isRetry?: boolean;
137
+ retriedFromId?: string;
138
+ }
139
+
140
+ export interface RetryMessageOptions {
141
+ messageId: string;
142
+ retriedByUserId?: string;
143
+ }
144
+
132
145
  export interface SendPushToUserMessage extends Omit<PushMessage, "tokens"> {
133
146
  userId: mongoose.Types.ObjectId | string;
134
147
  }
@@ -0,0 +1,520 @@
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 {DateTime} from "luxon";
8
+ import supertest from "supertest";
9
+
10
+ import {SendGridMailProvider} from "../adapters/sendgrid";
11
+ import {CommsApp} from "../commsApp";
12
+ import {CommsMessage} from "../models/commsMessage";
13
+ import type {DeliveryEvent, OptOutEvent} from "../types";
14
+
15
+ const PATH = "/comms/webhooks/sendgrid";
16
+ const MESSAGE_ID = "filterdrecv-abc123";
17
+ const SG_MESSAGE_ID = `${MESSAGE_ID}.filter0001.12345.1`;
18
+ const FROM_EMAIL = "notifications@example.com";
19
+
20
+ const createMailClient = (
21
+ messageId: string
22
+ ): {
23
+ send: (
24
+ message: Record<string, unknown>
25
+ ) => Promise<[{headers: Record<string, string>; statusCode: number}, Record<string, unknown>]>;
26
+ } => {
27
+ return {
28
+ send: async (): Promise<
29
+ [{headers: Record<string, string>; statusCode: number}, Record<string, unknown>]
30
+ > => {
31
+ return [{headers: {"x-message-id": messageId}, statusCode: 202}, {}];
32
+ },
33
+ };
34
+ };
35
+
36
+ const signPayload = ({
37
+ payload,
38
+ privateKey,
39
+ }: {
40
+ payload: string;
41
+ privateKey: crypto.KeyObject;
42
+ }): {signature: string; timestamp: string} => {
43
+ const timestamp = String(DateTime.utc().toUnixInteger());
44
+ const signer = crypto.createSign("SHA256");
45
+ signer.update(timestamp);
46
+ signer.update(payload);
47
+ signer.end();
48
+ return {signature: signer.sign(privateKey, "base64"), timestamp};
49
+ };
50
+
51
+ const buildSendGridCommsApp = ({
52
+ deliveries,
53
+ mailClient = createMailClient(MESSAGE_ID),
54
+ onOptOut,
55
+ verificationKey,
56
+ webhooks = new WebhooksApp({idempotency: {store: "memory"}}),
57
+ }: {
58
+ deliveries?: DeliveryEvent[];
59
+ mailClient?: {
60
+ send: (
61
+ message: Record<string, unknown>
62
+ ) => Promise<[{headers: Record<string, string>; statusCode: number}, Record<string, unknown>]>;
63
+ };
64
+ onOptOut?: (event: OptOutEvent) => Promise<void>;
65
+ verificationKey?: string;
66
+ webhooks?: WebhooksApp;
67
+ } = {}): {
68
+ app: Application;
69
+ comms: CommsApp;
70
+ keyPair: crypto.KeyPairKeyObjectResult;
71
+ } => {
72
+ const keyPair = crypto.generateKeyPairSync("ec", {namedCurve: "prime256v1"});
73
+ const publicKey = keyPair.publicKey.export({format: "pem", type: "spki"}).toString();
74
+ const mail = new SendGridMailProvider({
75
+ apiKey: "sg-test",
76
+ client: mailClient,
77
+ fromEmail: FROM_EMAIL,
78
+ webhookVerificationKey: verificationKey === undefined ? publicKey : verificationKey,
79
+ });
80
+ const comms = new CommsApp({
81
+ mail,
82
+ onDeliveryEvent: deliveries
83
+ ? async (event): Promise<void> => {
84
+ deliveries.push(event);
85
+ }
86
+ : undefined,
87
+ onOptOut,
88
+ webhooks,
89
+ });
90
+ const app = new TerrenoApp({
91
+ logRequests: false,
92
+ skipListen: true,
93
+ userModel: UserModel as unknown as UserModelType,
94
+ })
95
+ .register(comms)
96
+ .register(webhooks)
97
+ .build();
98
+ return {app, comms, keyPair};
99
+ };
100
+
101
+ const postSignedEvents = async ({
102
+ app,
103
+ events,
104
+ privateKey,
105
+ }: {
106
+ app: Application;
107
+ events: Record<string, unknown>[];
108
+ privateKey: crypto.KeyObject;
109
+ }): Promise<supertest.Response> => {
110
+ const payload = JSON.stringify(events);
111
+ const {signature, timestamp} = signPayload({payload, privateKey});
112
+ return supertest(app)
113
+ .post(PATH)
114
+ .set("Content-Type", "application/json")
115
+ .set("X-Twilio-Email-Event-Webhook-Timestamp", timestamp)
116
+ .set("X-Twilio-Email-Event-Webhook-Signature", signature)
117
+ .send(payload);
118
+ };
119
+
120
+ describe("SendGrid CommsApp webhooks", () => {
121
+ beforeEach(async (): Promise<void> => {
122
+ await setupDb();
123
+ await CommsMessage.deleteMany({});
124
+ Reflect.deleteProperty(process.env, "SENDGRID_WEBHOOK_VERIFICATION_KEY");
125
+ });
126
+
127
+ it("updates CommsMessage to delivered from a signed event", async (): Promise<void> => {
128
+ const {app, comms, keyPair} = buildSendGridCommsApp();
129
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
130
+ const res = await postSignedEvents({
131
+ app,
132
+ events: [
133
+ {
134
+ event: "delivered",
135
+ sg_event_id: "sg_delivered_1",
136
+ sg_message_id: SG_MESSAGE_ID,
137
+ },
138
+ ],
139
+ privateKey: keyPair.privateKey,
140
+ });
141
+ assert.equal(res.status, 200);
142
+ const row = await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID});
143
+ assert.equal(row.status, "delivered");
144
+ });
145
+
146
+ it("maps a signed bounce event to bounced + permanent", async (): Promise<void> => {
147
+ const {app, comms, keyPair} = buildSendGridCommsApp();
148
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
149
+ const res = await postSignedEvents({
150
+ app,
151
+ events: [
152
+ {
153
+ event: "bounce",
154
+ reason: "500 unknown recipient",
155
+ sg_event_id: "sg_bounce_1",
156
+ sg_message_id: SG_MESSAGE_ID,
157
+ type: "bounce",
158
+ },
159
+ ],
160
+ privateKey: keyPair.privateKey,
161
+ });
162
+ assert.equal(res.status, 200);
163
+ const row = await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID});
164
+ assert.equal(row.status, "bounced");
165
+ assert.equal(row.errorCode, "500 unknown recipient");
166
+ assert.equal(row.errorClass, "permanent");
167
+ });
168
+
169
+ it("fires onOptOut for a signed spamreport event", async (): Promise<void> => {
170
+ const optOuts: OptOutEvent[] = [];
171
+ const {app, comms, keyPair} = buildSendGridCommsApp({
172
+ onOptOut: async (event): Promise<void> => {
173
+ optOuts.push(event);
174
+ },
175
+ });
176
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
177
+ const res = await postSignedEvents({
178
+ app,
179
+ events: [
180
+ {
181
+ email: "person@example.com",
182
+ event: "spamreport",
183
+ sg_event_id: "sg_spam_1",
184
+ sg_message_id: SG_MESSAGE_ID,
185
+ },
186
+ ],
187
+ privateKey: keyPair.privateKey,
188
+ });
189
+ assert.equal(res.status, 200);
190
+ assert.equal(optOuts.length, 1);
191
+ assert.equal(optOuts[0]?.reason, "spamreport");
192
+ assert.equal(optOuts[0]?.to, "person@example.com");
193
+ const row = await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID});
194
+ assert.equal(row.status, "sent");
195
+ });
196
+
197
+ it("returns 401 webhook-signature-invalid for an unsigned payload", async (): Promise<void> => {
198
+ const {app} = buildSendGridCommsApp();
199
+ const res = await supertest(app)
200
+ .post(PATH)
201
+ .set("Content-Type", "application/json")
202
+ .send(`[{"sg_event_id":"sg_1","event":"delivered"}]`);
203
+ assert.equal(res.status, 401);
204
+ assert.equal(res.body.code, "webhook-signature-invalid");
205
+ });
206
+
207
+ it("does not apply a duplicate sg_event_id a second time", async (): Promise<void> => {
208
+ const deliveries: DeliveryEvent[] = [];
209
+ const {app, comms, keyPair} = buildSendGridCommsApp({deliveries});
210
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
211
+ const events = [
212
+ {
213
+ event: "delivered",
214
+ sg_event_id: "sg_dup_1",
215
+ sg_message_id: SG_MESSAGE_ID,
216
+ },
217
+ ];
218
+ const first = await postSignedEvents({app, events, privateKey: keyPair.privateKey});
219
+ const second = await postSignedEvents({app, events, privateKey: keyPair.privateKey});
220
+ assert.equal(first.status, 200);
221
+ assert.equal(second.status, 200);
222
+ assert.equal(deliveries.length, 1);
223
+ });
224
+
225
+ it("releases the claim when recordDeliveryEvent save fails", async (): Promise<void> => {
226
+ const {app, comms, keyPair} = buildSendGridCommsApp();
227
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
228
+ const saveSpy = spyOn(CommsMessage.prototype, "save").mockImplementation(
229
+ async (): Promise<never> => {
230
+ throw new Error("save failed");
231
+ }
232
+ );
233
+ const events = [
234
+ {
235
+ event: "delivered",
236
+ sg_event_id: "sg_save_fail_1",
237
+ sg_message_id: SG_MESSAGE_ID,
238
+ },
239
+ ];
240
+ const first = await postSignedEvents({app, events, privateKey: keyPair.privateKey});
241
+ saveSpy.mockRestore();
242
+ assert.equal(first.status, 500);
243
+ const second = await postSignedEvents({app, events, privateKey: keyPair.privateKey});
244
+ assert.equal(second.status, 200);
245
+ const row = await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID});
246
+ assert.equal(row.status, "delivered");
247
+ });
248
+
249
+ it("applies both events in a signed batch", async (): Promise<void> => {
250
+ const secondId = "filterdrecv-xyz789";
251
+ let call = 0;
252
+ const mailClient = {
253
+ send: async (): Promise<
254
+ [{headers: Record<string, string>; statusCode: number}, Record<string, unknown>]
255
+ > => {
256
+ call += 1;
257
+ const id = call === 1 ? MESSAGE_ID : secondId;
258
+ return [{headers: {"x-message-id": id}, statusCode: 202}, {}];
259
+ },
260
+ };
261
+ const {app, comms, keyPair} = buildSendGridCommsApp({mailClient});
262
+ await comms.service.sendMail({subject: "One", to: "one@example.com"});
263
+ await comms.service.sendMail({subject: "Two", to: "two@example.com"});
264
+ const res = await postSignedEvents({
265
+ app,
266
+ events: [
267
+ {
268
+ event: "delivered",
269
+ sg_event_id: "sg_batch_1",
270
+ sg_message_id: `${MESSAGE_ID}.recvd`,
271
+ },
272
+ {
273
+ event: "bounce",
274
+ reason: "bounce",
275
+ sg_event_id: "sg_batch_2",
276
+ sg_message_id: `${secondId}.recvd`,
277
+ type: "bounce",
278
+ },
279
+ ],
280
+ privateKey: keyPair.privateKey,
281
+ });
282
+ assert.equal(res.status, 200);
283
+ assert.equal(
284
+ (await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID})).status,
285
+ "delivered"
286
+ );
287
+ assert.equal(
288
+ (await CommsMessage.findExactlyOne({providerMessageId: secondId})).status,
289
+ "bounced"
290
+ );
291
+ });
292
+
293
+ it("does not mount SendGrid webhook paths when webhooks is omitted", async (): Promise<void> => {
294
+ const mail = new SendGridMailProvider({
295
+ apiKey: "sg-test",
296
+ client: createMailClient(MESSAGE_ID),
297
+ fromEmail: FROM_EMAIL,
298
+ webhookVerificationKey: "not-used",
299
+ });
300
+ const app = new TerrenoApp({
301
+ logRequests: false,
302
+ skipListen: true,
303
+ userModel: UserModel as unknown as UserModelType,
304
+ })
305
+ .register(new CommsApp({mail}))
306
+ .build();
307
+ const res = await supertest(app)
308
+ .post(PATH)
309
+ .set("Content-Type", "application/json")
310
+ .send(`[{"sg_event_id":"sg_1","event":"delivered"}]`);
311
+ assert.equal(res.status, 404);
312
+ });
313
+
314
+ it("skips SendGrid routes and logs when the verification key is missing", async (): Promise<void> => {
315
+ const errorSpy = spyOn(logger, "error");
316
+ const webhooks = new WebhooksApp({idempotency: {store: "memory"}});
317
+ const mail = new SendGridMailProvider({
318
+ apiKey: "sg-test",
319
+ client: createMailClient(MESSAGE_ID),
320
+ fromEmail: FROM_EMAIL,
321
+ });
322
+ const app = new TerrenoApp({
323
+ logRequests: false,
324
+ skipListen: true,
325
+ userModel: UserModel as unknown as UserModelType,
326
+ })
327
+ .register(new CommsApp({mail, webhooks}))
328
+ .register(webhooks)
329
+ .build();
330
+ const res = await supertest(app)
331
+ .post(PATH)
332
+ .set("Content-Type", "application/json")
333
+ .send(`[{"sg_event_id":"sg_1","event":"delivered"}]`);
334
+ assert.equal(res.status, 404);
335
+ assert.isTrue(
336
+ errorSpy.mock.calls.some((call) => String(call[0]).includes("Skipping SendGrid webhook"))
337
+ );
338
+ errorSpy.mockRestore();
339
+ });
340
+
341
+ it("maps dropped to failed", async (): Promise<void> => {
342
+ const {app, comms, keyPair} = buildSendGridCommsApp();
343
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
344
+ const res = await postSignedEvents({
345
+ app,
346
+ events: [
347
+ {
348
+ event: "dropped",
349
+ reason: "Bounced Address",
350
+ sg_event_id: "sg_dropped_1",
351
+ sg_message_id: `${MESSAGE_ID}.filter`,
352
+ },
353
+ ],
354
+ privateKey: keyPair.privateKey,
355
+ });
356
+ assert.equal(res.status, 200);
357
+ const stored = await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID});
358
+ assert.equal(stored.status, "failed");
359
+ assert.equal(stored.errorCode, "Bounced Address");
360
+ });
361
+
362
+ it("maps processed to sent", async (): Promise<void> => {
363
+ const {app, comms, keyPair} = buildSendGridCommsApp();
364
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
365
+ const res = await postSignedEvents({
366
+ app,
367
+ events: [
368
+ {
369
+ event: "processed",
370
+ sg_event_id: "sg_processed_1",
371
+ sg_message_id: `${MESSAGE_ID}.filter`,
372
+ },
373
+ ],
374
+ privateKey: keyPair.privateKey,
375
+ });
376
+ assert.equal(res.status, 200);
377
+ assert.equal(
378
+ (await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID})).status,
379
+ "sent"
380
+ );
381
+ });
382
+
383
+ it("skips unknown events, skipped events, and events without message ids", async (): Promise<void> => {
384
+ const {app, comms, keyPair} = buildSendGridCommsApp();
385
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
386
+ const res = await postSignedEvents({
387
+ app,
388
+ events: [
389
+ {event: "skipped", sg_event_id: "sg_skip_1", sg_message_id: `${MESSAGE_ID}.filter`},
390
+ {event: "delivered"},
391
+ {event: "bounce", type: "bounce"},
392
+ {notAnEvent: true},
393
+ ],
394
+ privateKey: keyPair.privateKey,
395
+ });
396
+ assert.equal(res.status, 200);
397
+ assert.equal(
398
+ (await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID})).status,
399
+ "sent"
400
+ );
401
+ });
402
+
403
+ it("uses bounce as errorCode when a bounce has no reason", async (): Promise<void> => {
404
+ const {app, comms, keyPair} = buildSendGridCommsApp();
405
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
406
+ const res = await postSignedEvents({
407
+ app,
408
+ events: [
409
+ {
410
+ event: "bounce",
411
+ sg_event_id: "sg_bounce_noreason",
412
+ sg_message_id: `${MESSAGE_ID}.filter`,
413
+ type: "bounce",
414
+ },
415
+ ],
416
+ privateKey: keyPair.privateKey,
417
+ });
418
+ assert.equal(res.status, 200);
419
+ const stored = await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID});
420
+ assert.equal(stored.status, "bounced");
421
+ assert.equal(stored.errorCode, "bounce");
422
+ });
423
+
424
+ it("maps a blocked bounce to bounced with transient errorClass", async (): Promise<void> => {
425
+ const {app, comms, keyPair} = buildSendGridCommsApp();
426
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
427
+ const res = await postSignedEvents({
428
+ app,
429
+ events: [
430
+ {
431
+ event: "bounce",
432
+ reason: "blocked",
433
+ sg_event_id: "sg_blocked_1",
434
+ sg_message_id: SG_MESSAGE_ID,
435
+ type: "blocked",
436
+ },
437
+ ],
438
+ privateKey: keyPair.privateKey,
439
+ });
440
+ assert.equal(res.status, 200);
441
+ const row = await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID});
442
+ assert.equal(row.status, "bounced");
443
+ assert.equal(row.errorClass, "transient");
444
+ assert.equal(row.errorCode, "blocked");
445
+ });
446
+
447
+ it("maps dropped and open events and ignores processed", async (): Promise<void> => {
448
+ const {app, comms, keyPair} = buildSendGridCommsApp();
449
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
450
+ const processed = await postSignedEvents({
451
+ app,
452
+ events: [{event: "processed", sg_event_id: "sg_proc_1", sg_message_id: SG_MESSAGE_ID}],
453
+ privateKey: keyPair.privateKey,
454
+ });
455
+ assert.equal(processed.status, 200);
456
+ assert.equal(
457
+ (await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID})).status,
458
+ "sent"
459
+ );
460
+ const dropped = await postSignedEvents({
461
+ app,
462
+ events: [
463
+ {
464
+ event: "dropped",
465
+ reason: "Bounced Address",
466
+ sg_event_id: "sg_drop_1",
467
+ sg_message_id: SG_MESSAGE_ID,
468
+ },
469
+ ],
470
+ privateKey: keyPair.privateKey,
471
+ });
472
+ assert.equal(dropped.status, 200);
473
+ const droppedRow = await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID});
474
+ assert.equal(droppedRow.status, "failed");
475
+ assert.equal(droppedRow.errorClass, "permanent");
476
+ const opened = await postSignedEvents({
477
+ app,
478
+ events: [{event: "open", sg_event_id: "sg_open_1", sg_message_id: SG_MESSAGE_ID}],
479
+ privateKey: keyPair.privateKey,
480
+ });
481
+ assert.equal(opened.status, 200);
482
+ assert.equal(
483
+ (await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID})).status,
484
+ "failed"
485
+ );
486
+ });
487
+
488
+ it("ignores a non-array body and events without sg_event_id", async (): Promise<void> => {
489
+ const {app, comms, keyPair} = buildSendGridCommsApp();
490
+ await comms.service.sendMail({subject: "Welcome", to: "person@example.com"});
491
+ const objectBody = JSON.stringify({event: "delivered", sg_event_id: "sg_obj"});
492
+ const {signature, timestamp} = signPayload({
493
+ payload: objectBody,
494
+ privateKey: keyPair.privateKey,
495
+ });
496
+ const objectRes = await supertest(app)
497
+ .post(PATH)
498
+ .set("Content-Type", "application/json")
499
+ .set("X-Twilio-Email-Event-Webhook-Timestamp", timestamp)
500
+ .set("X-Twilio-Email-Event-Webhook-Signature", signature)
501
+ .send(objectBody);
502
+ assert.equal(objectRes.status, 200);
503
+ const missingId = await postSignedEvents({
504
+ app,
505
+ events: [{event: "delivered", sg_message_id: SG_MESSAGE_ID}],
506
+ privateKey: keyPair.privateKey,
507
+ });
508
+ assert.equal(missingId.status, 200);
509
+ assert.equal(
510
+ (await CommsMessage.findExactlyOne({providerMessageId: MESSAGE_ID})).status,
511
+ "sent"
512
+ );
513
+ });
514
+
515
+ it("omits the SendGrid webhook path from OpenAPI", async (): Promise<void> => {
516
+ const {app} = buildSendGridCommsApp();
517
+ const response = await supertest(app).get("/openapi.json").expect(200);
518
+ assert.notProperty(response.body.paths, PATH);
519
+ });
520
+ });