@terreno/comms 56.0.0-beta.2

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/biome.jsonc +17 -0
  3. package/bunfig.toml +5 -0
  4. package/dist/adapters/console.d.ts +30 -0
  5. package/dist/adapters/console.js +122 -0
  6. package/dist/commsApp.d.ts +14 -0
  7. package/dist/commsApp.js +37 -0
  8. package/dist/commsService.d.ts +20 -0
  9. package/dist/commsService.js +386 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +19 -0
  12. package/dist/modelTypes.d.ts +53 -0
  13. package/dist/modelTypes.js +2 -0
  14. package/dist/models/commsMessage.d.ts +2 -0
  15. package/dist/models/commsMessage.js +119 -0
  16. package/dist/models/pushToken.d.ts +2 -0
  17. package/dist/models/pushToken.js +56 -0
  18. package/dist/routes/commsExplorer.d.ts +7 -0
  19. package/dist/routes/commsExplorer.js +147 -0
  20. package/dist/routes/pushTokens.d.ts +7 -0
  21. package/dist/routes/pushTokens.js +292 -0
  22. package/dist/templates.d.ts +10 -0
  23. package/dist/templates.js +32 -0
  24. package/dist/types.d.ts +78 -0
  25. package/dist/types.js +2 -0
  26. package/package.json +55 -0
  27. package/src/adapters/console.test.ts +227 -0
  28. package/src/adapters/console.ts +87 -0
  29. package/src/commsApp.test.ts +448 -0
  30. package/src/commsApp.ts +48 -0
  31. package/src/commsService.test.ts +570 -0
  32. package/src/commsService.ts +293 -0
  33. package/src/index.ts +45 -0
  34. package/src/modelTypes.ts +78 -0
  35. package/src/models/commsMessage.test.ts +53 -0
  36. package/src/models/commsMessage.ts +97 -0
  37. package/src/models/pushToken.test.ts +45 -0
  38. package/src/models/pushToken.ts +69 -0
  39. package/src/routes/commsExplorer.ts +114 -0
  40. package/src/routes/pushTokens.ts +265 -0
  41. package/src/templates.test.ts +37 -0
  42. package/src/templates.ts +31 -0
  43. package/src/tests/bunSetup.ts +14 -0
  44. package/src/types.ts +93 -0
  45. package/tsconfig.json +32 -0
@@ -0,0 +1,570 @@
1
+ import {beforeEach, describe, it} from "bun:test";
2
+ import {type APIError, isAPIError} from "@terreno/api";
3
+ import {setupDb} from "@terreno/api/testing";
4
+ import {assert} from "chai";
5
+ import {DateTime} from "luxon";
6
+ import mongoose from "mongoose";
7
+ import {CommsService} from "./commsService";
8
+ import type {
9
+ CheckVerificationOptions,
10
+ MailMessage,
11
+ MailProvider,
12
+ PushMessage,
13
+ PushProvider,
14
+ SendResult,
15
+ SmsProvider,
16
+ StartVerificationOptions,
17
+ VerificationProvider,
18
+ } from "./index";
19
+ import {CommsMessage, PushToken} from "./index";
20
+
21
+ const captureError = async (operation: () => Promise<unknown>): Promise<unknown> => {
22
+ try {
23
+ await operation();
24
+ return undefined;
25
+ } catch (error: unknown) {
26
+ return error;
27
+ }
28
+ };
29
+
30
+ describe("CommsService", () => {
31
+ beforeEach(async (): Promise<void> => {
32
+ await setupDb();
33
+ await Promise.all([CommsMessage.deleteMany({}), PushToken.deleteMany({})]);
34
+ });
35
+
36
+ it("delegates every configured channel and records each attempt", async (): Promise<void> => {
37
+ const userId = new mongoose.Types.ObjectId();
38
+ await PushToken.upsert(
39
+ {token: "ExponentPushToken[test]"},
40
+ {
41
+ active: true,
42
+ lastSeenAt: DateTime.utc().toJSDate(),
43
+ platform: "ios",
44
+ userId,
45
+ }
46
+ );
47
+
48
+ let deliveredMail: MailMessage | undefined;
49
+ const mail: MailProvider = {
50
+ id: "memory-mail",
51
+ sendMail: async (message: MailMessage): Promise<SendResult> => {
52
+ deliveredMail = message;
53
+ return {accepted: true, providerMessageId: "mail-1"};
54
+ },
55
+ };
56
+ const sms: SmsProvider = {
57
+ id: "memory-sms",
58
+ sendSms: async (): Promise<SendResult> => ({
59
+ accepted: true,
60
+ providerMessageId: "sms-1",
61
+ }),
62
+ };
63
+ const push: PushProvider = {
64
+ id: "memory-push",
65
+ sendPush: async (message: PushMessage): Promise<SendResult[]> =>
66
+ message.tokens.map((_token, index) => ({
67
+ accepted: true,
68
+ providerMessageId: `push-${index}`,
69
+ })),
70
+ };
71
+ const verification: VerificationProvider = {
72
+ checkVerification: async (): Promise<{valid: boolean}> => ({valid: true}),
73
+ id: "memory-verification",
74
+ startVerification: async (): Promise<SendResult> => ({
75
+ accepted: true,
76
+ providerMessageId: "verification-1",
77
+ }),
78
+ };
79
+ const service = new CommsService({
80
+ defaultFrom: "sender@example.com",
81
+ mail,
82
+ push,
83
+ sms,
84
+ verification,
85
+ });
86
+
87
+ const mailResult = await service.sendMail({subject: "Welcome", to: "person@example.com"});
88
+ const smsResult = await service.sendSms({body: "Hello", to: "+15555550100"});
89
+ const pushResults = await service.sendPushToUser({body: "Hello", title: "Title", userId});
90
+ const startResult = await service.startVerification({
91
+ channel: "sms",
92
+ to: "+15555550100",
93
+ });
94
+ const checkResult = await service.checkVerification({
95
+ code: "123456",
96
+ to: "+15555550100",
97
+ });
98
+
99
+ assert.equal(deliveredMail?.from, "sender@example.com");
100
+ assert.isTrue(mailResult.accepted);
101
+ assert.isTrue(smsResult.accepted);
102
+ assert.lengthOf(pushResults, 1);
103
+ assert.isTrue(startResult.accepted);
104
+ assert.isTrue(checkResult.valid);
105
+ assert.equal(await CommsMessage.countDocuments(), 5);
106
+ assert.equal(await CommsMessage.countDocuments({to: "[redacted]"}), 5);
107
+ assert.equal(
108
+ await CommsMessage.countDocuments({
109
+ channel: "mail",
110
+ provider: "memory-mail",
111
+ providerMessageId: "mail-1",
112
+ status: "sent",
113
+ }),
114
+ 1
115
+ );
116
+ assert.equal(
117
+ await CommsMessage.countDocuments({
118
+ channel: "sms",
119
+ provider: "memory-sms",
120
+ providerMessageId: "sms-1",
121
+ status: "sent",
122
+ }),
123
+ 1
124
+ );
125
+ assert.equal(
126
+ await CommsMessage.countDocuments({
127
+ channel: "push",
128
+ provider: "memory-push",
129
+ providerMessageId: "push-0",
130
+ status: "sent",
131
+ }),
132
+ 1
133
+ );
134
+ assert.equal(
135
+ await CommsMessage.countDocuments({
136
+ channel: "verification",
137
+ provider: "memory-verification",
138
+ status: "sent",
139
+ }),
140
+ 2
141
+ );
142
+ });
143
+
144
+ it("supports starting and checking both SMS and email verification", async (): Promise<void> => {
145
+ const started: StartVerificationOptions[] = [];
146
+ const checked: CheckVerificationOptions[] = [];
147
+ const verification: VerificationProvider = {
148
+ checkVerification: async (options): Promise<{valid: boolean}> => {
149
+ checked.push(options);
150
+ return {valid: true};
151
+ },
152
+ id: "multi-channel-verification",
153
+ startVerification: async (options): Promise<SendResult> => {
154
+ started.push(options);
155
+ return {accepted: true};
156
+ },
157
+ };
158
+ const service = new CommsService({verification});
159
+
160
+ const smsStart = await service.startVerification({
161
+ channel: "sms",
162
+ to: "+15555550100",
163
+ });
164
+ const emailStart = await service.startVerification({
165
+ channel: "email",
166
+ to: "person@example.com",
167
+ });
168
+ const smsCheck = await service.checkVerification({
169
+ code: "123456",
170
+ to: "+15555550100",
171
+ });
172
+ const emailCheck = await service.checkVerification({
173
+ code: "654321",
174
+ to: "person@example.com",
175
+ });
176
+
177
+ assert.isTrue(smsStart.accepted);
178
+ assert.isTrue(emailStart.accepted);
179
+ assert.isTrue(smsCheck.valid);
180
+ assert.isTrue(emailCheck.valid);
181
+ assert.deepEqual(started, [
182
+ {channel: "sms", to: "+15555550100"},
183
+ {channel: "email", to: "person@example.com"},
184
+ ]);
185
+ assert.deepEqual(checked, [
186
+ {code: "123456", to: "+15555550100"},
187
+ {code: "654321", to: "person@example.com"},
188
+ ]);
189
+ assert.equal(
190
+ await CommsMessage.countDocuments({
191
+ channel: "verification",
192
+ provider: "multi-channel-verification",
193
+ status: "sent",
194
+ to: "[redacted]",
195
+ }),
196
+ 4
197
+ );
198
+ assert.equal(await CommsMessage.countDocuments({to: "+15555550100"}), 0);
199
+ assert.equal(await CommsMessage.countDocuments({to: "person@example.com"}), 0);
200
+ assert.equal(await CommsMessage.countDocuments({"metadata.verificationChannel": "sms"}), 1);
201
+ assert.equal(await CommsMessage.countDocuments({"metadata.verificationChannel": "email"}), 1);
202
+ const serializedAuditRows = JSON.stringify(
203
+ await CommsMessage.find({provider: "multi-channel-verification"})
204
+ );
205
+ for (const sensitiveValue of ["+15555550100", "person@example.com", "123456", "654321"]) {
206
+ assert.notInclude(serializedAuditRows, sensitiveValue);
207
+ }
208
+ });
209
+
210
+ it("uses console providers for every unconfigured channel outside production", async (): Promise<void> => {
211
+ const userId = new mongoose.Types.ObjectId();
212
+ await PushToken.upsert(
213
+ {token: "ExponentPushToken[console]"},
214
+ {
215
+ active: true,
216
+ lastSeenAt: DateTime.utc().toJSDate(),
217
+ platform: "ios",
218
+ userId,
219
+ }
220
+ );
221
+ const service = new CommsService();
222
+
223
+ assert.isTrue(
224
+ (await service.sendMail({subject: "Welcome", to: "person@example.com"})).accepted
225
+ );
226
+ assert.isTrue((await service.sendSms({body: "Hello", to: "+15555550100"})).accepted);
227
+ assert.isTrue(
228
+ (await service.sendPushToUser({body: "Hello", title: "Title", userId}))[0]?.accepted
229
+ );
230
+ assert.isTrue(
231
+ (
232
+ await service.startVerification({
233
+ channel: "sms",
234
+ to: "+15555550100",
235
+ })
236
+ ).accepted
237
+ );
238
+ assert.isTrue(
239
+ (
240
+ await service.checkVerification({
241
+ code: "123456",
242
+ to: "+15555550100",
243
+ })
244
+ ).valid
245
+ );
246
+ assert.isTrue(
247
+ (
248
+ await service.startVerification({
249
+ channel: "email",
250
+ to: "person@example.com",
251
+ })
252
+ ).accepted
253
+ );
254
+ assert.isTrue(
255
+ (
256
+ await service.checkVerification({
257
+ code: "654321",
258
+ to: "person@example.com",
259
+ })
260
+ ).valid
261
+ );
262
+ assert.equal(await CommsMessage.countDocuments(), 7);
263
+ assert.equal(await CommsMessage.countDocuments({provider: "console", to: "[redacted]"}), 7);
264
+ assert.equal(await CommsMessage.countDocuments({to: "person@example.com"}), 0);
265
+ });
266
+
267
+ it("throws a 501 APIError for every unconfigured channel in production", async (): Promise<void> => {
268
+ process.env.NODE_ENV = "production";
269
+ const service = new CommsService();
270
+ const userId = new mongoose.Types.ObjectId();
271
+ const operations = [
272
+ (): Promise<unknown> => service.sendMail({subject: "Welcome", to: "person@example.com"}),
273
+ (): Promise<unknown> => service.sendSms({body: "Hello", to: "+15555550100"}),
274
+ (): Promise<unknown> => service.sendPushToUser({body: "Hello", title: "Title", userId}),
275
+ (): Promise<unknown> => service.startVerification({channel: "sms", to: "+15555550100"}),
276
+ (): Promise<unknown> => service.checkVerification({code: "123456", to: "+15555550100"}),
277
+ (): Promise<unknown> =>
278
+ service.startVerification({channel: "email", to: "person@example.com"}),
279
+ (): Promise<unknown> => service.checkVerification({code: "654321", to: "person@example.com"}),
280
+ ];
281
+
282
+ for (const operation of operations) {
283
+ const error = await captureError(operation);
284
+ assert.isTrue(isAPIError(error));
285
+ assert.equal((error as APIError).status, 501);
286
+ assert.equal((error as APIError).title, "Comms channel not configured");
287
+ }
288
+ assert.equal(await CommsMessage.countDocuments(), 0);
289
+ });
290
+
291
+ it("records failed rows when configured providers throw", async (): Promise<void> => {
292
+ const userId = new mongoose.Types.ObjectId();
293
+ await PushToken.upsert(
294
+ {token: "ExponentPushToken[throw]"},
295
+ {
296
+ active: true,
297
+ lastSeenAt: DateTime.utc().toJSDate(),
298
+ platform: "ios",
299
+ userId,
300
+ }
301
+ );
302
+ const throwProviderError = async (): Promise<never> => {
303
+ throw new Error("Provider unavailable");
304
+ };
305
+ const service = new CommsService({
306
+ mail: {id: "throw-mail", sendMail: throwProviderError},
307
+ push: {id: "throw-push", sendPush: throwProviderError},
308
+ sms: {id: "throw-sms", sendSms: throwProviderError},
309
+ verification: {
310
+ checkVerification: throwProviderError,
311
+ id: "throw-verification",
312
+ startVerification: throwProviderError,
313
+ },
314
+ });
315
+ const operations = [
316
+ (): Promise<unknown> => service.sendMail({subject: "Welcome", to: "person@example.com"}),
317
+ (): Promise<unknown> => service.sendSms({body: "Hello", to: "+15555550100"}),
318
+ (): Promise<unknown> => service.sendPushToUser({body: "Hello", title: "Title", userId}),
319
+ (): Promise<unknown> => service.startVerification({channel: "sms", to: "+15555550100"}),
320
+ (): Promise<unknown> => service.checkVerification({code: "654321", to: "+15555550100"}),
321
+ (): Promise<unknown> =>
322
+ service.startVerification({channel: "email", to: "person@example.com"}),
323
+ (): Promise<unknown> => service.checkVerification({code: "123456", to: "person@example.com"}),
324
+ ];
325
+
326
+ for (const operation of operations) {
327
+ const error = await captureError(operation);
328
+ assert.instanceOf(error, Error);
329
+ }
330
+
331
+ assert.equal(await CommsMessage.countDocuments({status: "failed"}), 7);
332
+ assert.equal(await CommsMessage.countDocuments({to: "[redacted]"}), 7);
333
+ assert.equal(
334
+ await CommsMessage.countDocuments({
335
+ channel: "mail",
336
+ error: "Provider send failed",
337
+ provider: "throw-mail",
338
+ status: "failed",
339
+ }),
340
+ 1
341
+ );
342
+ assert.equal(
343
+ await CommsMessage.countDocuments({
344
+ channel: "verification",
345
+ error: "Provider send failed",
346
+ "metadata.verificationChannel": "sms",
347
+ provider: "throw-verification",
348
+ status: "failed",
349
+ }),
350
+ 1
351
+ );
352
+ assert.equal(
353
+ await CommsMessage.countDocuments({
354
+ channel: "sms",
355
+ error: "Provider send failed",
356
+ provider: "throw-sms",
357
+ status: "failed",
358
+ }),
359
+ 1
360
+ );
361
+ assert.equal(
362
+ await CommsMessage.countDocuments({
363
+ channel: "push",
364
+ error: "Provider send failed",
365
+ provider: "throw-push",
366
+ status: "failed",
367
+ }),
368
+ 1
369
+ );
370
+ assert.equal(
371
+ await CommsMessage.countDocuments({
372
+ channel: "verification",
373
+ error: "Provider send failed",
374
+ "metadata.verificationChannel": "email",
375
+ provider: "throw-verification",
376
+ status: "failed",
377
+ }),
378
+ 1
379
+ );
380
+ assert.equal(
381
+ await CommsMessage.countDocuments({
382
+ channel: "verification",
383
+ error: "Provider check failed",
384
+ provider: "throw-verification",
385
+ status: "failed",
386
+ }),
387
+ 2
388
+ );
389
+ assert.equal(await CommsMessage.countDocuments({to: "+15555550100"}), 0);
390
+ assert.equal(await CommsMessage.countDocuments({to: "person@example.com"}), 0);
391
+ });
392
+
393
+ it("logs missing push results as temporary failures without pruning tokens", async (): Promise<void> => {
394
+ const userId = new mongoose.Types.ObjectId();
395
+ const tokens = await Promise.all(
396
+ ["first", "second"].map(
397
+ async (suffix): Promise<Awaited<ReturnType<typeof PushToken.upsert>>> =>
398
+ PushToken.upsert(
399
+ {token: `ExponentPushToken[${suffix}]`},
400
+ {
401
+ active: true,
402
+ lastSeenAt: DateTime.utc().toJSDate(),
403
+ platform: "ios",
404
+ userId,
405
+ }
406
+ )
407
+ )
408
+ );
409
+ const push: PushProvider = {
410
+ id: "short-results",
411
+ sendPush: async (): Promise<SendResult[]> => [{accepted: true}],
412
+ };
413
+
414
+ const results = await new CommsService({push}).sendPushToUser({
415
+ body: "Hello",
416
+ title: "Title",
417
+ userId,
418
+ });
419
+
420
+ assert.lengthOf(results, 2);
421
+ assert.isTrue(results[0]?.accepted);
422
+ assert.isFalse(results[1]?.accepted);
423
+ assert.equal(await CommsMessage.countDocuments({status: "sent"}), 1);
424
+ assert.equal(await CommsMessage.countDocuments({status: "failed"}), 1);
425
+ for (const token of tokens) {
426
+ const updated = await PushToken.findExactlyOne({_id: token._id});
427
+ assert.isTrue(updated.active);
428
+ }
429
+ });
430
+
431
+ it("ignores provider push results that do not correspond to a token", async (): Promise<void> => {
432
+ const userId = new mongoose.Types.ObjectId();
433
+ await PushToken.upsert(
434
+ {token: "ExponentPushToken[single]"},
435
+ {
436
+ active: true,
437
+ lastSeenAt: DateTime.utc().toJSDate(),
438
+ platform: "ios",
439
+ userId,
440
+ }
441
+ );
442
+ const push: PushProvider = {
443
+ id: "extra-results",
444
+ sendPush: async (): Promise<SendResult[]> => [
445
+ {accepted: true, providerMessageId: "expected"},
446
+ {accepted: false, isPermanentFailure: true, providerMessageId: "extra"},
447
+ ],
448
+ };
449
+
450
+ const results = await new CommsService({push}).sendPushToUser({
451
+ body: "Hello",
452
+ title: "Title",
453
+ userId,
454
+ });
455
+
456
+ assert.lengthOf(results, 1);
457
+ assert.equal(results[0]?.providerMessageId, "expected");
458
+ assert.equal(await CommsMessage.countDocuments(), 1);
459
+ assert.equal(await CommsMessage.countDocuments({providerMessageId: "extra"}), 0);
460
+ });
461
+
462
+ it("keeps tokens active after explicit non-permanent provider failures", async (): Promise<void> => {
463
+ const userId = new mongoose.Types.ObjectId();
464
+ const token = await PushToken.upsert(
465
+ {token: "ExponentPushToken[temporary]"},
466
+ {
467
+ active: true,
468
+ lastSeenAt: DateTime.utc().toJSDate(),
469
+ platform: "ios",
470
+ userId,
471
+ }
472
+ );
473
+ const push: PushProvider = {
474
+ id: "temporary-failure",
475
+ sendPush: async (): Promise<SendResult[]> => [
476
+ {accepted: false, error: "Rate limited", isPermanentFailure: false},
477
+ ],
478
+ };
479
+
480
+ await new CommsService({push}).sendPushToUser({body: "Hello", title: "Title", userId});
481
+
482
+ const updated = await PushToken.findExactlyOne({_id: token._id});
483
+ assert.isTrue(updated.active);
484
+ });
485
+
486
+ it("records an invalid verification check as failed", async (): Promise<void> => {
487
+ const verification: VerificationProvider = {
488
+ checkVerification: async ({code}): Promise<{error?: string; valid: boolean}> =>
489
+ code === "missing-reason"
490
+ ? {valid: false}
491
+ : {
492
+ error: "Verification expired",
493
+ valid: false,
494
+ },
495
+ id: "memory-verification",
496
+ startVerification: async (): Promise<SendResult> => ({accepted: true}),
497
+ };
498
+
499
+ const service = new CommsService({verification});
500
+ const emailResult = await service.checkVerification({
501
+ code: "wrong-code",
502
+ to: "person@example.com",
503
+ });
504
+ const smsResult = await service.checkVerification({
505
+ code: "wrong-code",
506
+ to: "+15555550100",
507
+ });
508
+ const fallbackResult = await service.checkVerification({
509
+ code: "missing-reason",
510
+ to: "fallback@example.com",
511
+ });
512
+
513
+ assert.isFalse(emailResult.valid);
514
+ assert.equal(emailResult.error, "Verification expired");
515
+ assert.isFalse(smsResult.valid);
516
+ assert.equal(smsResult.error, "Verification expired");
517
+ assert.isFalse(fallbackResult.valid);
518
+ assert.isUndefined(fallbackResult.error);
519
+ assert.equal(
520
+ await CommsMessage.countDocuments({
521
+ channel: "verification",
522
+ error: "Verification expired",
523
+ status: "failed",
524
+ to: "[redacted]",
525
+ }),
526
+ 2
527
+ );
528
+ assert.equal(
529
+ await CommsMessage.countDocuments({
530
+ channel: "verification",
531
+ error: "Verification check failed",
532
+ status: "failed",
533
+ to: "[redacted]",
534
+ }),
535
+ 1
536
+ );
537
+ assert.equal(await CommsMessage.countDocuments({to: "person@example.com"}), 0);
538
+ assert.equal(await CommsMessage.countDocuments({to: "+15555550100"}), 0);
539
+ const serializedAuditRows = JSON.stringify(
540
+ await CommsMessage.find({channel: "verification", status: "failed"})
541
+ );
542
+ for (const sensitiveValue of ["wrong-code", "missing-reason", "fallback@example.com"]) {
543
+ assert.notInclude(serializedAuditRows, sensitiveValue);
544
+ }
545
+ });
546
+
547
+ it("deactivates push tokens after permanent provider failures", async (): Promise<void> => {
548
+ const userId = new mongoose.Types.ObjectId();
549
+ const token = await PushToken.upsert(
550
+ {token: "ExponentPushToken[dead]"},
551
+ {
552
+ active: true,
553
+ lastSeenAt: DateTime.utc().toJSDate(),
554
+ platform: "ios",
555
+ userId,
556
+ }
557
+ );
558
+ const push: PushProvider = {
559
+ id: "memory-push",
560
+ sendPush: async (): Promise<SendResult[]> => [
561
+ {accepted: false, error: "DeviceNotRegistered", isPermanentFailure: true},
562
+ ],
563
+ };
564
+
565
+ await new CommsService({push}).sendPushToUser({body: "Hello", title: "Title", userId});
566
+
567
+ const updated = await PushToken.findExactlyOne({_id: token._id});
568
+ assert.isFalse(updated.active);
569
+ });
570
+ });