@terreno/comms 57.16.1 → 57.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commsApp.d.ts +2 -2
- package/dist/commsApp.js +2 -1
- package/dist/commsService.d.ts +11 -1
- package/dist/commsService.js +44 -3
- package/dist/modelTypes.d.ts +1 -0
- package/dist/models/pushToken.js +4 -0
- package/dist/routes/pushTokens.js +5 -1
- package/dist/types.d.ts +17 -0
- package/package.json +3 -3
- package/src/adapters/twilioVerify.test.ts +171 -1
- package/src/commsApp.test.ts +227 -1
- package/src/commsApp.ts +3 -1
- package/src/commsService.test.ts +415 -0
- package/src/commsService.ts +59 -4
- package/src/modelTypes.ts +1 -0
- package/src/models/pushToken.ts +4 -0
- package/src/routes/pushTokens.ts +16 -5
- package/src/types.ts +18 -0
package/src/commsApp.test.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {beforeEach, describe, it} from "bun:test";
|
|
1
|
+
import {beforeEach, describe, it, spyOn} from "bun:test";
|
|
2
2
|
import {
|
|
3
3
|
addAuthRoutes,
|
|
4
4
|
apiErrorMiddleware,
|
|
5
5
|
apiUnauthorizedMiddleware,
|
|
6
|
+
logger,
|
|
6
7
|
setupAuth,
|
|
7
8
|
TerrenoApp,
|
|
8
9
|
type UserModel as UserModelType,
|
|
@@ -17,6 +18,7 @@ import type TestAgent from "supertest/lib/agent";
|
|
|
17
18
|
import {CommsApp, getCommsService} from "./commsApp";
|
|
18
19
|
import {CommsMessage} from "./models/commsMessage";
|
|
19
20
|
import {PushToken} from "./models/pushToken";
|
|
21
|
+
import type {PushProvider, SendResult} from "./types";
|
|
20
22
|
|
|
21
23
|
const buildApp = (): express.Application => {
|
|
22
24
|
const app = getBaseServer();
|
|
@@ -310,6 +312,106 @@ describe("CommsApp", () => {
|
|
|
310
312
|
.expect(400);
|
|
311
313
|
});
|
|
312
314
|
|
|
315
|
+
it("filters the push-token list by active state and platform", async (): Promise<void> => {
|
|
316
|
+
const app = buildApp();
|
|
317
|
+
const owner = await authAsUser(app, "notAdmin");
|
|
318
|
+
const ios = await owner
|
|
319
|
+
.post("/comms/pushTokens")
|
|
320
|
+
.send({platform: "ios", token: "ExponentPushToken[ios]"})
|
|
321
|
+
.expect(201);
|
|
322
|
+
await owner
|
|
323
|
+
.post("/comms/pushTokens")
|
|
324
|
+
.send({platform: "android", token: "ExponentPushToken[android]"})
|
|
325
|
+
.expect(201);
|
|
326
|
+
await owner.delete(`/comms/pushTokens/${ios.body.data._id}`).expect(204);
|
|
327
|
+
|
|
328
|
+
const active = await owner.get("/comms/pushTokens?active=true").expect(200);
|
|
329
|
+
const inactive = await owner.get("/comms/pushTokens?active=false").expect(200);
|
|
330
|
+
const iosOnly = await owner.get("/comms/pushTokens?platform=ios").expect(200);
|
|
331
|
+
const ignoredFilter = await owner.get("/comms/pushTokens?active=maybe").expect(200);
|
|
332
|
+
|
|
333
|
+
assert.deepEqual(
|
|
334
|
+
active.body.data.map((row: {token: string}) => row.token),
|
|
335
|
+
["ExponentPushToken[android]"]
|
|
336
|
+
);
|
|
337
|
+
assert.deepEqual(
|
|
338
|
+
inactive.body.data.map((row: {token: string}) => row.token),
|
|
339
|
+
["ExponentPushToken[ios]"]
|
|
340
|
+
);
|
|
341
|
+
assert.deepEqual(
|
|
342
|
+
iosOnly.body.data.map((row: {active: boolean; token: string}) => [row.token, row.active]),
|
|
343
|
+
[["ExponentPushToken[ios]", false]]
|
|
344
|
+
);
|
|
345
|
+
assert.equal(ignoredFilter.body.total, 2);
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
it("surfaces non-conflict storage failures while claiming a push token", async (): Promise<void> => {
|
|
349
|
+
const app = buildApp();
|
|
350
|
+
const owner = await authAsUser(app, "notAdmin");
|
|
351
|
+
const duplicateKey = Object.assign(new Error("E11000 duplicate key"), {code: 11000});
|
|
352
|
+
const claim = spyOn(PushToken, "findOneAndUpdate");
|
|
353
|
+
try {
|
|
354
|
+
claim.mockImplementationOnce((() => {
|
|
355
|
+
throw new Error("primary stepped down");
|
|
356
|
+
}) as never);
|
|
357
|
+
await owner
|
|
358
|
+
.post("/comms/pushTokens")
|
|
359
|
+
.send({platform: "ios", token: "ExponentPushToken[outage]"})
|
|
360
|
+
.expect(500);
|
|
361
|
+
|
|
362
|
+
// A lost race retries once; a different failure on the retry is not reported as a conflict.
|
|
363
|
+
claim
|
|
364
|
+
.mockImplementationOnce((() => {
|
|
365
|
+
throw duplicateKey;
|
|
366
|
+
}) as never)
|
|
367
|
+
.mockImplementationOnce((() => {
|
|
368
|
+
throw new Error("primary stepped down");
|
|
369
|
+
}) as never);
|
|
370
|
+
await owner
|
|
371
|
+
.post("/comms/pushTokens")
|
|
372
|
+
.send({platform: "ios", token: "ExponentPushToken[outage]"})
|
|
373
|
+
.expect(500);
|
|
374
|
+
|
|
375
|
+
claim.mockImplementationOnce((async () => ({
|
|
376
|
+
lastErrorObject: {updatedExisting: false},
|
|
377
|
+
value: null,
|
|
378
|
+
})) as never);
|
|
379
|
+
const empty = await owner
|
|
380
|
+
.post("/comms/pushTokens")
|
|
381
|
+
.send({platform: "ios", token: "ExponentPushToken[outage]"})
|
|
382
|
+
.expect(500);
|
|
383
|
+
assert.equal(empty.body.title, "Push token claim returned no document");
|
|
384
|
+
} finally {
|
|
385
|
+
claim.mockRestore();
|
|
386
|
+
}
|
|
387
|
+
assert.equal(await PushToken.countDocuments({token: "ExponentPushToken[outage]"}), 0);
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
it("logs when the push-token index cannot be built at registration", async (): Promise<void> => {
|
|
391
|
+
const init = spyOn(PushToken, "init").mockImplementation((async () => {
|
|
392
|
+
throw new Error("index build refused");
|
|
393
|
+
}) as never);
|
|
394
|
+
const errorSpy = spyOn(logger, "error").mockImplementation(() => logger);
|
|
395
|
+
try {
|
|
396
|
+
new CommsApp({logMessages: false}).register(getBaseServer());
|
|
397
|
+
// The index build runs in the background, so wait for its rejection handler.
|
|
398
|
+
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
399
|
+
|
|
400
|
+
const messages = errorSpy.mock.calls.map((call) => String(call[0]));
|
|
401
|
+
assert.isTrue(
|
|
402
|
+
messages.some(
|
|
403
|
+
(message) =>
|
|
404
|
+
message.includes("[comms] Failed to build PushToken indexes") &&
|
|
405
|
+
message.includes("index build refused")
|
|
406
|
+
),
|
|
407
|
+
messages.join("\n")
|
|
408
|
+
);
|
|
409
|
+
} finally {
|
|
410
|
+
init.mockRestore();
|
|
411
|
+
errorSpy.mockRestore();
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
|
|
313
415
|
it("exposes a paginated, filterable delivery explorer to admins only", async (): Promise<void> => {
|
|
314
416
|
const app = buildApp();
|
|
315
417
|
const admin = await authAsUser(app, "admin");
|
|
@@ -458,4 +560,128 @@ describe("CommsApp", () => {
|
|
|
458
560
|
assert.includeMembers(operation.tags, ["comms"]);
|
|
459
561
|
}
|
|
460
562
|
});
|
|
563
|
+
|
|
564
|
+
describe("push delivery and the account lifecycle", () => {
|
|
565
|
+
let sentTokens: string[][];
|
|
566
|
+
const push: PushProvider = {
|
|
567
|
+
id: "lifecycle-push",
|
|
568
|
+
sendPush: async (message): Promise<SendResult[]> => {
|
|
569
|
+
sentTokens.push(message.tokens);
|
|
570
|
+
return message.tokens.map((): SendResult => ({accepted: true}));
|
|
571
|
+
},
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
const buildLifecycleApp = (): {app: express.Application; plugin: CommsApp} => {
|
|
575
|
+
const plugin = new CommsApp({logMessages: false, push});
|
|
576
|
+
const app = new TerrenoApp({
|
|
577
|
+
skipListen: true,
|
|
578
|
+
userModel: UserModel as unknown as UserModelType,
|
|
579
|
+
})
|
|
580
|
+
.register(plugin)
|
|
581
|
+
.build();
|
|
582
|
+
return {app, plugin};
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
const registerDevice = async (agent: TestAgent, token: string): Promise<void> => {
|
|
586
|
+
await agent.post("/comms/pushTokens").send({platform: "ios", token}).expect(201);
|
|
587
|
+
};
|
|
588
|
+
|
|
589
|
+
beforeEach((): void => {
|
|
590
|
+
sentTokens = [];
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
it("stops pushing to a device registered before the user's credentials changed", async (): Promise<void> => {
|
|
594
|
+
const {app, plugin} = buildLifecycleApp();
|
|
595
|
+
const {agent, userId} = await signUpAgent(app, "epoch@example.com");
|
|
596
|
+
await registerDevice(agent, "ExponentPushToken[epoch]");
|
|
597
|
+
assert.lengthOf(await plugin.service.sendPushToUser({body: "B", title: "T", userId}), 1);
|
|
598
|
+
|
|
599
|
+
await UserModel.updateOne({_id: userId}, {$inc: {tokenEpoch: 1}});
|
|
600
|
+
const afterReset = await plugin.service.sendPushToUser({body: "B", title: "T", userId});
|
|
601
|
+
|
|
602
|
+
assert.lengthOf(afterReset, 0);
|
|
603
|
+
assert.deepEqual(sentTokens, [["ExponentPushToken[epoch]"]]);
|
|
604
|
+
const stored = await PushToken.findExactlyOne({token: "ExponentPushToken[epoch]"});
|
|
605
|
+
assert.isFalse(stored.active);
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
it("pushes again after the device registers under the new credentials", async (): Promise<void> => {
|
|
609
|
+
const {app, plugin} = buildLifecycleApp();
|
|
610
|
+
const {agent, userId} = await signUpAgent(app, "reregister@example.com");
|
|
611
|
+
await registerDevice(agent, "ExponentPushToken[again]");
|
|
612
|
+
await UserModel.updateOne({_id: userId}, {$inc: {tokenEpoch: 1}});
|
|
613
|
+
await plugin.service.sendPushToUser({body: "B", title: "T", userId});
|
|
614
|
+
|
|
615
|
+
await agent
|
|
616
|
+
.post("/comms/pushTokens")
|
|
617
|
+
.send({platform: "ios", token: "ExponentPushToken[again]"})
|
|
618
|
+
.expect(200);
|
|
619
|
+
const results = await plugin.service.sendPushToUser({body: "B", title: "T", userId});
|
|
620
|
+
|
|
621
|
+
assert.lengthOf(results, 1);
|
|
622
|
+
assert.deepEqual(sentTokens, [["ExponentPushToken[again]"]]);
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
it("does not push to a disabled user and releases their devices", async (): Promise<void> => {
|
|
626
|
+
const {app, plugin} = buildLifecycleApp();
|
|
627
|
+
const {agent, userId} = await signUpAgent(app, "disabled@example.com");
|
|
628
|
+
await registerDevice(agent, "ExponentPushToken[disabled]");
|
|
629
|
+
|
|
630
|
+
await UserModel.updateOne({_id: userId}, {$set: {disabled: true}});
|
|
631
|
+
const results = await plugin.service.sendPushToUser({body: "B", title: "T", userId});
|
|
632
|
+
|
|
633
|
+
assert.lengthOf(results, 0);
|
|
634
|
+
assert.lengthOf(sentTokens, 0);
|
|
635
|
+
assert.equal(await PushToken.countDocuments({active: true}), 0);
|
|
636
|
+
});
|
|
637
|
+
|
|
638
|
+
it("does not push to a user that no longer exists", async (): Promise<void> => {
|
|
639
|
+
const {app, plugin} = buildLifecycleApp();
|
|
640
|
+
const {agent, userId} = await signUpAgent(app, "deleted@example.com");
|
|
641
|
+
await registerDevice(agent, "ExponentPushToken[deleted]");
|
|
642
|
+
|
|
643
|
+
await UserModel.deleteOne({_id: userId});
|
|
644
|
+
const results = await plugin.service.sendPushToUser({body: "B", title: "T", userId});
|
|
645
|
+
|
|
646
|
+
assert.lengthOf(results, 0);
|
|
647
|
+
assert.lengthOf(sentTokens, 0);
|
|
648
|
+
assert.equal(await PushToken.countDocuments({active: true}), 0);
|
|
649
|
+
});
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
describe("auth recovery mail", () => {
|
|
653
|
+
const buildRecoveryApp = (): express.Application => {
|
|
654
|
+
const plugin = new CommsApp();
|
|
655
|
+
return new TerrenoApp({
|
|
656
|
+
authOptions: {
|
|
657
|
+
publicAppUrl: "https://app.example.com",
|
|
658
|
+
sendMail: async (message): Promise<void> => {
|
|
659
|
+
await getCommsService().sendMail(message);
|
|
660
|
+
},
|
|
661
|
+
},
|
|
662
|
+
skipListen: true,
|
|
663
|
+
userModel: UserModel as unknown as UserModelType,
|
|
664
|
+
})
|
|
665
|
+
.register(plugin)
|
|
666
|
+
.build();
|
|
667
|
+
};
|
|
668
|
+
|
|
669
|
+
it("keeps the reset link out of the message log and the dashboard", async (): Promise<void> => {
|
|
670
|
+
const app = buildRecoveryApp();
|
|
671
|
+
const admin = await authAsUser(app, "admin");
|
|
672
|
+
|
|
673
|
+
await supertest(app)
|
|
674
|
+
.post("/auth/forgotPassword")
|
|
675
|
+
.send({email: "notAdmin@example.com"})
|
|
676
|
+
.expect(202);
|
|
677
|
+
|
|
678
|
+
const rows = await CommsMessage.find({channel: "mail"});
|
|
679
|
+
assert.lengthOf(rows, 1);
|
|
680
|
+
assert.isUndefined(rows[0]?.payload);
|
|
681
|
+
assert.equal(rows[0]?.subject, "Reset your password");
|
|
682
|
+
const list = await admin.get("/comms/messages").expect(200);
|
|
683
|
+
assert.notInclude(JSON.stringify(list.body), "token=");
|
|
684
|
+
assert.notInclude(JSON.stringify(list.body), "notAdmin@example.com");
|
|
685
|
+
});
|
|
686
|
+
});
|
|
461
687
|
});
|
package/src/commsApp.ts
CHANGED
|
@@ -2,6 +2,7 @@ import {
|
|
|
2
2
|
type AdminContribution,
|
|
3
3
|
APIError,
|
|
4
4
|
logger,
|
|
5
|
+
type TerrenoApp,
|
|
5
6
|
type TerrenoPlugin,
|
|
6
7
|
type WebhooksApp,
|
|
7
8
|
} from "@terreno/api";
|
|
@@ -39,9 +40,10 @@ export class CommsApp implements TerrenoPlugin {
|
|
|
39
40
|
this.service = new CommsService(this.options);
|
|
40
41
|
}
|
|
41
42
|
|
|
42
|
-
register(app: express.Application, openApi?: unknown): void {
|
|
43
|
+
register(app: express.Application, openApi?: unknown, terrenoApp?: TerrenoApp): void {
|
|
43
44
|
const basePath = this.options.basePath ?? "/comms";
|
|
44
45
|
registeredCommsService = this.service;
|
|
46
|
+
this.service.setUserModel(terrenoApp?.getUserModel());
|
|
45
47
|
|
|
46
48
|
// Atomic push-token registration depends on the unique token index to reject concurrent
|
|
47
49
|
// claims, so build it explicitly instead of relying on Mongoose autoIndex being enabled.
|
package/src/commsService.test.ts
CHANGED
|
@@ -409,6 +409,65 @@ describe("CommsService", () => {
|
|
|
409
409
|
assert.equal(await CommsMessage.countDocuments({to: "person@example.com"}), 0);
|
|
410
410
|
});
|
|
411
411
|
|
|
412
|
+
it("stores no payload for mail marked sensitive, on the first attempt or the retry", async (): Promise<void> => {
|
|
413
|
+
let calls = 0;
|
|
414
|
+
const mail: MailProvider = {
|
|
415
|
+
id: "flaky-mail",
|
|
416
|
+
sendMail: async (): Promise<SendResult> => {
|
|
417
|
+
calls += 1;
|
|
418
|
+
return calls === 1 ? {accepted: false, errorClass: "transient"} : {accepted: true};
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
const service = new CommsService({mail});
|
|
422
|
+
|
|
423
|
+
await service.sendMail({
|
|
424
|
+
sensitive: true,
|
|
425
|
+
subject: "Reset",
|
|
426
|
+
text: "token=abc",
|
|
427
|
+
to: "a@example.com",
|
|
428
|
+
});
|
|
429
|
+
await service.sendMail(
|
|
430
|
+
{subject: "Verify", text: "token=def", to: "b@example.com"},
|
|
431
|
+
{sensitive: true}
|
|
432
|
+
);
|
|
433
|
+
|
|
434
|
+
const rows = await CommsMessage.find({channel: "mail"});
|
|
435
|
+
assert.lengthOf(rows, 2);
|
|
436
|
+
for (const row of rows) {
|
|
437
|
+
assert.isUndefined(row.payload);
|
|
438
|
+
assert.isUndefined(row.payloadExpiresAt);
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
it("skips push for a soft-deleted user from the configured user model", async (): Promise<void> => {
|
|
443
|
+
const userId = new mongoose.Types.ObjectId();
|
|
444
|
+
await PushToken.upsert(
|
|
445
|
+
{token: "ExponentPushToken[soft-deleted]"},
|
|
446
|
+
{active: true, lastSeenAt: DateTime.utc().toJSDate(), platform: "ios", userId}
|
|
447
|
+
);
|
|
448
|
+
const sent: string[][] = [];
|
|
449
|
+
const push: PushProvider = {
|
|
450
|
+
id: "soft-deleted",
|
|
451
|
+
sendPush: async (message): Promise<SendResult[]> => {
|
|
452
|
+
sent.push(message.tokens);
|
|
453
|
+
return [{accepted: true}];
|
|
454
|
+
},
|
|
455
|
+
};
|
|
456
|
+
const service = new CommsService({
|
|
457
|
+
push,
|
|
458
|
+
userModel: {findById: async (): Promise<unknown> => ({_id: userId, deleted: true})},
|
|
459
|
+
});
|
|
460
|
+
service.setUserModel({findById: async (): Promise<unknown> => ({_id: userId})});
|
|
461
|
+
|
|
462
|
+
const results = await service.sendPushToUser({body: "Hello", title: "Title", userId});
|
|
463
|
+
|
|
464
|
+
assert.lengthOf(results, 0);
|
|
465
|
+
assert.lengthOf(sent, 0);
|
|
466
|
+
assert.isFalse(
|
|
467
|
+
(await PushToken.findExactlyOne({token: "ExponentPushToken[soft-deleted]"})).active
|
|
468
|
+
);
|
|
469
|
+
});
|
|
470
|
+
|
|
412
471
|
it("logs missing push results as temporary failures without pruning tokens", async (): Promise<void> => {
|
|
413
472
|
const userId = new mongoose.Types.ObjectId();
|
|
414
473
|
const tokens = await Promise.all(
|
|
@@ -1418,4 +1477,360 @@ describe("CommsService", () => {
|
|
|
1418
1477
|
assert.isUndefined(row.payload);
|
|
1419
1478
|
assert.deepEqual(row.metadata?.hookErrors, {redactPayload: ["hook-threw"]});
|
|
1420
1479
|
});
|
|
1480
|
+
it("cancels SMS and verification sends from beforeSend without calling providers", async (): Promise<void> => {
|
|
1481
|
+
let providerCalls = 0;
|
|
1482
|
+
const service = new CommsService({
|
|
1483
|
+
beforeSend: async (): Promise<{cancel: boolean}> => ({cancel: true}),
|
|
1484
|
+
sms: {
|
|
1485
|
+
id: "cancel-sms",
|
|
1486
|
+
sendSms: async (): Promise<SendResult> => {
|
|
1487
|
+
providerCalls += 1;
|
|
1488
|
+
return {accepted: true};
|
|
1489
|
+
},
|
|
1490
|
+
},
|
|
1491
|
+
verification: {
|
|
1492
|
+
checkVerification: async (): Promise<{valid: boolean}> => ({valid: true}),
|
|
1493
|
+
id: "cancel-verification",
|
|
1494
|
+
startVerification: async (): Promise<SendResult> => {
|
|
1495
|
+
providerCalls += 1;
|
|
1496
|
+
return {accepted: true};
|
|
1497
|
+
},
|
|
1498
|
+
},
|
|
1499
|
+
});
|
|
1500
|
+
|
|
1501
|
+
const sms = await service.sendSms({body: "Hello", to: "+15555550100"});
|
|
1502
|
+
const verification = await service.startVerification({channel: "email", to: "a@example.com"});
|
|
1503
|
+
|
|
1504
|
+
assert.equal(providerCalls, 0);
|
|
1505
|
+
assert.equal(sms.errorCode, "before-send-cancel");
|
|
1506
|
+
assert.equal(verification.errorCode, "before-send-cancel");
|
|
1507
|
+
assert.isUndefined(verification.loggedMessageId);
|
|
1508
|
+
const smsRow = await CommsMessage.findExactlyOne({channel: "sms", status: "cancelled"});
|
|
1509
|
+
const verificationRow = await CommsMessage.findExactlyOne({
|
|
1510
|
+
channel: "verification",
|
|
1511
|
+
status: "cancelled",
|
|
1512
|
+
});
|
|
1513
|
+
assert.equal(sms.loggedMessageId, String(smsRow._id));
|
|
1514
|
+
assert.equal(smsRow.provider, "cancel-sms");
|
|
1515
|
+
assert.equal(verificationRow.provider, "cancel-verification");
|
|
1516
|
+
assert.equal(
|
|
1517
|
+
(verificationRow.metadata as {verificationChannel?: string}).verificationChannel,
|
|
1518
|
+
"email"
|
|
1519
|
+
);
|
|
1520
|
+
});
|
|
1521
|
+
|
|
1522
|
+
it("returns no push results when beforeSend removes every token", async (): Promise<void> => {
|
|
1523
|
+
const userId = new mongoose.Types.ObjectId();
|
|
1524
|
+
await PushToken.upsert(
|
|
1525
|
+
{token: "ExponentPushToken[filtered]"},
|
|
1526
|
+
{active: true, lastSeenAt: DateTime.utc().toJSDate(), platform: "ios", userId}
|
|
1527
|
+
);
|
|
1528
|
+
let providerCalls = 0;
|
|
1529
|
+
const service = new CommsService({
|
|
1530
|
+
beforeSend: async (context): Promise<{message: PushMessage}> => ({
|
|
1531
|
+
message: {...(context.message as PushMessage), tokens: []},
|
|
1532
|
+
}),
|
|
1533
|
+
push: {
|
|
1534
|
+
id: "filtered-push",
|
|
1535
|
+
sendPush: async (): Promise<SendResult[]> => {
|
|
1536
|
+
providerCalls += 1;
|
|
1537
|
+
return [];
|
|
1538
|
+
},
|
|
1539
|
+
},
|
|
1540
|
+
});
|
|
1541
|
+
|
|
1542
|
+
const results = await service.sendPushToUser({body: "Hello", title: "Title", userId});
|
|
1543
|
+
|
|
1544
|
+
assert.deepEqual(results, []);
|
|
1545
|
+
assert.equal(providerCalls, 0);
|
|
1546
|
+
assert.equal(await CommsMessage.countDocuments(), 0);
|
|
1547
|
+
});
|
|
1548
|
+
|
|
1549
|
+
it("reports each channel as configured only with a provider in production", (): void => {
|
|
1550
|
+
const verification: VerificationProvider = {
|
|
1551
|
+
checkVerification: async (): Promise<{valid: boolean}> => ({valid: true}),
|
|
1552
|
+
id: "configured-verification",
|
|
1553
|
+
startVerification: async (): Promise<SendResult> => ({accepted: true}),
|
|
1554
|
+
};
|
|
1555
|
+
const smsOnly = new CommsService({
|
|
1556
|
+
sms: {id: "configured-sms", sendSms: async (): Promise<SendResult> => ({accepted: true})},
|
|
1557
|
+
});
|
|
1558
|
+
const pushAndVerification = new CommsService({
|
|
1559
|
+
push: {id: "configured-push", sendPush: async (): Promise<SendResult[]> => []},
|
|
1560
|
+
verification,
|
|
1561
|
+
});
|
|
1562
|
+
const channels = ["mail", "sms", "push", "verification"] as const;
|
|
1563
|
+
|
|
1564
|
+
assert.deepEqual(
|
|
1565
|
+
channels.map((channel) => smsOnly.isChannelConfigured(channel)),
|
|
1566
|
+
[true, true, true, true]
|
|
1567
|
+
);
|
|
1568
|
+
process.env.NODE_ENV = "production";
|
|
1569
|
+
assert.deepEqual(
|
|
1570
|
+
channels.map((channel) => smsOnly.isChannelConfigured(channel)),
|
|
1571
|
+
[false, true, false, false]
|
|
1572
|
+
);
|
|
1573
|
+
assert.deepEqual(
|
|
1574
|
+
channels.map((channel) => pushAndVerification.isChannelConfigured(channel)),
|
|
1575
|
+
[false, false, true, true]
|
|
1576
|
+
);
|
|
1577
|
+
});
|
|
1578
|
+
|
|
1579
|
+
it("retries a failed SMS from its stored payload", async (): Promise<void> => {
|
|
1580
|
+
const sent: Array<{body: string; to: string}> = [];
|
|
1581
|
+
const service = new CommsService({
|
|
1582
|
+
sms: {
|
|
1583
|
+
id: "retry-sms",
|
|
1584
|
+
sendSms: async (message): Promise<SendResult> => {
|
|
1585
|
+
sent.push({body: message.body, to: message.to});
|
|
1586
|
+
return {accepted: true, providerMessageId: "sms-retry-ok"};
|
|
1587
|
+
},
|
|
1588
|
+
},
|
|
1589
|
+
});
|
|
1590
|
+
const original = await CommsMessage.create({
|
|
1591
|
+
channel: "sms",
|
|
1592
|
+
payload: {body: "Your appointment is tomorrow", to: "+15555550100"},
|
|
1593
|
+
provider: "retry-sms",
|
|
1594
|
+
status: "failed",
|
|
1595
|
+
to: "+15555550100",
|
|
1596
|
+
});
|
|
1597
|
+
|
|
1598
|
+
const retried = await service.retryMessage({
|
|
1599
|
+
messageId: String(original._id),
|
|
1600
|
+
retriedByUserId: "admin-1",
|
|
1601
|
+
});
|
|
1602
|
+
|
|
1603
|
+
assert.deepEqual(sent, [{body: "Your appointment is tomorrow", to: "+15555550100"}]);
|
|
1604
|
+
assert.equal(retried.providerMessageId, "sms-retry-ok");
|
|
1605
|
+
assert.equal(String(retried.retriedFromId), String(original._id));
|
|
1606
|
+
assert.equal((retried.metadata as {retriedByUserId?: string}).retriedByUserId, "admin-1");
|
|
1607
|
+
const updatedOriginal = await CommsMessage.findExactlyOne({_id: original._id});
|
|
1608
|
+
assert.equal(String(updatedOriginal.retriedById), String(retried._id));
|
|
1609
|
+
});
|
|
1610
|
+
|
|
1611
|
+
it("retries a failed push to the linked user's current devices", async (): Promise<void> => {
|
|
1612
|
+
const userId = new mongoose.Types.ObjectId();
|
|
1613
|
+
await PushToken.upsert(
|
|
1614
|
+
{token: "ExponentPushToken[retry]"},
|
|
1615
|
+
{active: true, lastSeenAt: DateTime.utc().toJSDate(), platform: "ios", userId}
|
|
1616
|
+
);
|
|
1617
|
+
const sent: PushMessage[] = [];
|
|
1618
|
+
const service = new CommsService({
|
|
1619
|
+
push: {
|
|
1620
|
+
id: "retry-push",
|
|
1621
|
+
sendPush: async (message: PushMessage): Promise<SendResult[]> => {
|
|
1622
|
+
sent.push(message);
|
|
1623
|
+
return message.tokens.map(() => ({accepted: true, providerMessageId: "push-retry-ok"}));
|
|
1624
|
+
},
|
|
1625
|
+
},
|
|
1626
|
+
});
|
|
1627
|
+
const original = await CommsMessage.create({
|
|
1628
|
+
channel: "push",
|
|
1629
|
+
payload: {
|
|
1630
|
+
badge: 2,
|
|
1631
|
+
body: "New message",
|
|
1632
|
+
data: {screen: "inbox"},
|
|
1633
|
+
sound: null,
|
|
1634
|
+
title: "Inbox",
|
|
1635
|
+
},
|
|
1636
|
+
provider: "retry-push",
|
|
1637
|
+
status: "failed",
|
|
1638
|
+
to: "ExponentPushToken[old]",
|
|
1639
|
+
userId,
|
|
1640
|
+
});
|
|
1641
|
+
|
|
1642
|
+
const retried = await service.retryMessage({messageId: String(original._id)});
|
|
1643
|
+
|
|
1644
|
+
assert.deepEqual(sent, [
|
|
1645
|
+
{
|
|
1646
|
+
badge: 2,
|
|
1647
|
+
body: "New message",
|
|
1648
|
+
data: {screen: "inbox"},
|
|
1649
|
+
sound: null,
|
|
1650
|
+
title: "Inbox",
|
|
1651
|
+
tokens: ["ExponentPushToken[retry]"],
|
|
1652
|
+
},
|
|
1653
|
+
]);
|
|
1654
|
+
assert.equal(retried.providerMessageId, "push-retry-ok");
|
|
1655
|
+
assert.equal(String(retried.retriedFromId), String(original._id));
|
|
1656
|
+
});
|
|
1657
|
+
|
|
1658
|
+
it("refuses to retry a push without a linked user", async (): Promise<void> => {
|
|
1659
|
+
const service = new CommsService({
|
|
1660
|
+
push: {id: "orphan-push", sendPush: async (): Promise<SendResult[]> => []},
|
|
1661
|
+
});
|
|
1662
|
+
const original = await CommsMessage.create({
|
|
1663
|
+
channel: "push",
|
|
1664
|
+
payload: {body: "Hello", title: "Title"},
|
|
1665
|
+
provider: "orphan-push",
|
|
1666
|
+
status: "failed",
|
|
1667
|
+
to: "ExponentPushToken[orphan]",
|
|
1668
|
+
});
|
|
1669
|
+
|
|
1670
|
+
const error = await captureError(() => service.retryMessage({messageId: String(original._id)}));
|
|
1671
|
+
|
|
1672
|
+
assert.isTrue(isAPIError(error));
|
|
1673
|
+
assert.equal((error as APIError).status, 400);
|
|
1674
|
+
assert.equal((error as APIError).title, "Push retries require a linked user");
|
|
1675
|
+
});
|
|
1676
|
+
|
|
1677
|
+
it("returns 404 when retrying a malformed or unknown message id", async (): Promise<void> => {
|
|
1678
|
+
const service = new CommsService();
|
|
1679
|
+
|
|
1680
|
+
for (const messageId of ["not-an-object-id", String(new mongoose.Types.ObjectId())]) {
|
|
1681
|
+
const error = await captureError(() => service.retryMessage({messageId}));
|
|
1682
|
+
assert.isTrue(isAPIError(error));
|
|
1683
|
+
assert.equal((error as APIError).status, 404);
|
|
1684
|
+
assert.equal((error as APIError).title, "Comms message not found");
|
|
1685
|
+
}
|
|
1686
|
+
});
|
|
1687
|
+
|
|
1688
|
+
it("records a throwing onRetry hook on each retried push token", async (): Promise<void> => {
|
|
1689
|
+
const userId = new mongoose.Types.ObjectId();
|
|
1690
|
+
await PushToken.upsert(
|
|
1691
|
+
{token: "ExponentPushToken[flaky]"},
|
|
1692
|
+
{active: true, lastSeenAt: DateTime.utc().toJSDate(), platform: "ios", userId}
|
|
1693
|
+
);
|
|
1694
|
+
let pushCalls = 0;
|
|
1695
|
+
const service = new CommsService({
|
|
1696
|
+
onRetry: async (): Promise<void> => {
|
|
1697
|
+
throw new Error("onRetry boom");
|
|
1698
|
+
},
|
|
1699
|
+
push: {
|
|
1700
|
+
id: "flaky-push",
|
|
1701
|
+
sendPush: async (message: PushMessage): Promise<SendResult[]> => {
|
|
1702
|
+
pushCalls += 1;
|
|
1703
|
+
return message.tokens.map(
|
|
1704
|
+
(): SendResult =>
|
|
1705
|
+
pushCalls === 1
|
|
1706
|
+
? {accepted: false, error: "Timeout", errorClass: "transient"}
|
|
1707
|
+
: {accepted: true, providerMessageId: "flaky-retry-ok"}
|
|
1708
|
+
);
|
|
1709
|
+
},
|
|
1710
|
+
},
|
|
1711
|
+
});
|
|
1712
|
+
|
|
1713
|
+
const results = await service.sendPushToUser({body: "Hello", title: "Title", userId});
|
|
1714
|
+
|
|
1715
|
+
assert.equal(pushCalls, 2);
|
|
1716
|
+
assert.isTrue(results[0]?.accepted);
|
|
1717
|
+
const row = await CommsMessage.findExactlyOne({providerMessageId: "flaky-retry-ok"});
|
|
1718
|
+
assert.equal(row.attemptCount, 2);
|
|
1719
|
+
assert.deepEqual(row.metadata?.hookErrors, {onRetry: ["hook-threw"]});
|
|
1720
|
+
});
|
|
1721
|
+
|
|
1722
|
+
it("retries a transient SMS failure even when message logging is off", async (): Promise<void> => {
|
|
1723
|
+
let smsCalls = 0;
|
|
1724
|
+
const service = new CommsService({
|
|
1725
|
+
logMessages: false,
|
|
1726
|
+
sms: {
|
|
1727
|
+
id: "unlogged-sms",
|
|
1728
|
+
sendSms: async (): Promise<SendResult> => {
|
|
1729
|
+
smsCalls += 1;
|
|
1730
|
+
return smsCalls === 1
|
|
1731
|
+
? {accepted: false, error: "Timeout", errorClass: "transient"}
|
|
1732
|
+
: {accepted: true, providerMessageId: "unlogged-ok"};
|
|
1733
|
+
},
|
|
1734
|
+
},
|
|
1735
|
+
});
|
|
1736
|
+
|
|
1737
|
+
const result = await service.sendSms({body: "Hello", to: "+15555550100"});
|
|
1738
|
+
|
|
1739
|
+
assert.equal(smsCalls, 2);
|
|
1740
|
+
assert.isTrue(result.accepted);
|
|
1741
|
+
assert.isUndefined(result.loggedMessageId);
|
|
1742
|
+
assert.equal(await CommsMessage.countDocuments(), 0);
|
|
1743
|
+
});
|
|
1744
|
+
|
|
1745
|
+
it("skips delivery events without a provider message id after running the hook", async (): Promise<void> => {
|
|
1746
|
+
const events: string[] = [];
|
|
1747
|
+
const service = new CommsService({
|
|
1748
|
+
onDeliveryEvent: async (event): Promise<void> => {
|
|
1749
|
+
events.push(event.status);
|
|
1750
|
+
},
|
|
1751
|
+
});
|
|
1752
|
+
const row = await CommsMessage.create({
|
|
1753
|
+
channel: "mail",
|
|
1754
|
+
provider: "events-mail",
|
|
1755
|
+
status: "sent",
|
|
1756
|
+
to: "person@example.com",
|
|
1757
|
+
});
|
|
1758
|
+
|
|
1759
|
+
await service.recordDeliveryEvent({channel: "mail", status: "delivered"});
|
|
1760
|
+
|
|
1761
|
+
assert.deepEqual(events, ["delivered"]);
|
|
1762
|
+
const unchanged = await CommsMessage.findExactlyOne({_id: row._id});
|
|
1763
|
+
assert.equal(unchanged.status, "sent");
|
|
1764
|
+
});
|
|
1765
|
+
|
|
1766
|
+
it("leaves inactive push tokens alone and logs deactivation failures", async (): Promise<void> => {
|
|
1767
|
+
const userId = new mongoose.Types.ObjectId();
|
|
1768
|
+
const inactive = await PushToken.upsert(
|
|
1769
|
+
{token: "ExponentPushToken[inactive]"},
|
|
1770
|
+
{active: false, lastSeenAt: DateTime.utc().toJSDate(), platform: "ios", userId}
|
|
1771
|
+
);
|
|
1772
|
+
const service = new CommsService();
|
|
1773
|
+
const saveSpy = spyOn(PushToken.prototype, "save");
|
|
1774
|
+
|
|
1775
|
+
await service.deactivatePushToken("ExponentPushToken[inactive]");
|
|
1776
|
+
await service.deactivatePushToken("ExponentPushToken[unknown]");
|
|
1777
|
+
assert.equal(saveSpy.mock.calls.length, 0);
|
|
1778
|
+
saveSpy.mockRestore();
|
|
1779
|
+
const stored = await PushToken.findExactlyOne({_id: inactive._id});
|
|
1780
|
+
assert.isFalse(stored.active);
|
|
1781
|
+
|
|
1782
|
+
const warnSpy = spyOn(logger, "warn").mockImplementation(() => logger);
|
|
1783
|
+
const findSpy = spyOn(PushToken, "findOneOrNone").mockImplementation((async () => {
|
|
1784
|
+
throw new Error("lookup failed");
|
|
1785
|
+
}) as never);
|
|
1786
|
+
try {
|
|
1787
|
+
await service.deactivatePushToken("ExponentPushToken[inactive]");
|
|
1788
|
+
assert.isTrue(
|
|
1789
|
+
warnSpy.mock.calls.some((call) =>
|
|
1790
|
+
String(call[0]).includes("Failed to deactivate push token: Error: lookup failed")
|
|
1791
|
+
)
|
|
1792
|
+
);
|
|
1793
|
+
} finally {
|
|
1794
|
+
findSpy.mockRestore();
|
|
1795
|
+
warnSpy.mockRestore();
|
|
1796
|
+
}
|
|
1797
|
+
});
|
|
1798
|
+
|
|
1799
|
+
it("keeps the send outcome when hook errors cannot be saved to the log", async (): Promise<void> => {
|
|
1800
|
+
const service = new CommsService({
|
|
1801
|
+
mail: {
|
|
1802
|
+
id: "hook-save-fail-mail",
|
|
1803
|
+
sendMail: async (): Promise<SendResult> => ({accepted: true, providerMessageId: "m-1"}),
|
|
1804
|
+
},
|
|
1805
|
+
onSend: async (): Promise<void> => {
|
|
1806
|
+
throw new Error("onSend boom");
|
|
1807
|
+
},
|
|
1808
|
+
});
|
|
1809
|
+
const originalSave = CommsMessage.prototype.save;
|
|
1810
|
+
const saveSpy = spyOn(CommsMessage.prototype, "save").mockImplementation(function (
|
|
1811
|
+
this: InstanceType<typeof CommsMessage>,
|
|
1812
|
+
...args: Parameters<typeof originalSave>
|
|
1813
|
+
) {
|
|
1814
|
+
if (!this.isNew && (this.metadata as {hookErrors?: unknown} | undefined)?.hookErrors) {
|
|
1815
|
+
return Promise.reject(new Error("metadata write failed"));
|
|
1816
|
+
}
|
|
1817
|
+
return originalSave.apply(this, args);
|
|
1818
|
+
} as typeof originalSave);
|
|
1819
|
+
const warnSpy = spyOn(logger, "warn").mockImplementation(() => logger);
|
|
1820
|
+
try {
|
|
1821
|
+
const result = await service.sendMail({subject: "Welcome", to: "person@example.com"});
|
|
1822
|
+
|
|
1823
|
+
assert.isTrue(result.accepted);
|
|
1824
|
+
assert.isTrue(
|
|
1825
|
+
warnSpy.mock.calls.some((call) =>
|
|
1826
|
+
String(call[0]).includes("Failed to record hook errors: Error: metadata write failed")
|
|
1827
|
+
)
|
|
1828
|
+
);
|
|
1829
|
+
const row = await CommsMessage.findExactlyOne({_id: result.loggedMessageId});
|
|
1830
|
+
assert.isUndefined(row.metadata?.hookErrors);
|
|
1831
|
+
} finally {
|
|
1832
|
+
saveSpy.mockRestore();
|
|
1833
|
+
warnSpy.mockRestore();
|
|
1834
|
+
}
|
|
1835
|
+
});
|
|
1421
1836
|
});
|