@terreno/comms 57.16.2 → 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.
@@ -1,4 +1,4 @@
1
- import { type AdminContribution, type TerrenoPlugin, type WebhooksApp } from "@terreno/api";
1
+ import { type AdminContribution, type TerrenoApp, type TerrenoPlugin, type WebhooksApp } from "@terreno/api";
2
2
  import type express from "express";
3
3
  import { CommsService } from "./commsService";
4
4
  import type { CommsOptions } from "./types";
@@ -12,6 +12,6 @@ export declare class CommsApp implements TerrenoPlugin {
12
12
  readonly service: CommsService;
13
13
  private readonly options;
14
14
  constructor(options?: CommsAppOptions);
15
- register(app: express.Application, openApi?: unknown): void;
15
+ register(app: express.Application, openApi?: unknown, terrenoApp?: TerrenoApp): void;
16
16
  adminContribution(): AdminContribution;
17
17
  }
package/dist/commsApp.js CHANGED
@@ -23,9 +23,10 @@ class CommsApp {
23
23
  this.options = options ?? {};
24
24
  this.service = new commsService_1.CommsService(this.options);
25
25
  }
26
- register(app, openApi) {
26
+ register(app, openApi, terrenoApp) {
27
27
  const basePath = this.options.basePath ?? "/comms";
28
28
  registeredCommsService = this.service;
29
+ this.service.setUserModel(terrenoApp?.getUserModel());
29
30
  // Atomic push-token registration depends on the unique token index to reject concurrent
30
31
  // claims, so build it explicitly instead of relying on Mongoose autoIndex being enabled.
31
32
  void pushToken_1.PushToken.init().catch((error) => {
@@ -1,12 +1,22 @@
1
1
  import type { CommsMessageDocument } from "./modelTypes";
2
- import type { CheckVerificationOptions, CommsChannel, CommsOptions, CommsSendOptions, DeliveryEvent, MailMessage, OptOutEvent, RetryMessageOptions, SendPushToUserMessage, SendResult, SmsMessage, StartVerificationOptions, VerificationResult } from "./types";
2
+ import type { CheckVerificationOptions, CommsChannel, CommsOptions, CommsSendOptions, CommsUserModel, DeliveryEvent, MailMessage, OptOutEvent, RetryMessageOptions, SendPushToUserMessage, SendResult, SmsMessage, StartVerificationOptions, VerificationResult } from "./types";
3
3
  export declare class CommsService {
4
4
  private readonly options;
5
5
  private readonly consoleMail;
6
6
  private readonly consolePush;
7
7
  private readonly consoleSms;
8
8
  private readonly consoleVerification;
9
+ private userModel;
10
+ private readonly sensitiveContexts;
9
11
  constructor(options?: CommsOptions);
12
+ /** Set the user model push delivery checks, unless one was passed in the options. */
13
+ setUserModel(userModel: CommsUserModel | undefined): void;
14
+ /**
15
+ * The user's devices that may receive push: none for a missing, disabled, or deleted user, and
16
+ * only those registered under the user's current tokenEpoch, so a password reset or session
17
+ * revocation ends delivery to devices bound before it. The rest are released.
18
+ */
19
+ private deliverablePushTokens;
10
20
  recordDeliveryEvent(event: DeliveryEvent): Promise<void>;
11
21
  recordOptOut(event: OptOutEvent): Promise<void>;
12
22
  deactivatePushToken(token: string): Promise<void>;
@@ -34,8 +34,45 @@ class CommsService {
34
34
  consolePush = new console_1.ConsolePushProvider();
35
35
  consoleSms = new console_1.ConsoleSmsProvider();
36
36
  consoleVerification = new console_1.ConsoleVerificationProvider();
37
+ userModel;
38
+ // Sends whose payload carries a secret; their log rows keep no payload.
39
+ sensitiveContexts = new WeakSet();
37
40
  constructor(options) {
38
41
  this.options = options ?? {};
42
+ this.userModel = this.options.userModel;
43
+ }
44
+ /** Set the user model push delivery checks, unless one was passed in the options. */
45
+ setUserModel(userModel) {
46
+ this.userModel = this.options.userModel ?? userModel;
47
+ }
48
+ /**
49
+ * The user's devices that may receive push: none for a missing, disabled, or deleted user, and
50
+ * only those registered under the user's current tokenEpoch, so a password reset or session
51
+ * revocation ends delivery to devices bound before it. The rest are released.
52
+ */
53
+ async deliverablePushTokens(userId) {
54
+ const tokens = await pushToken_1.PushToken.find({ active: true, userId });
55
+ if (!this.userModel || tokens.length === 0) {
56
+ return tokens;
57
+ }
58
+ const user = (await this.userModel.findById(userId));
59
+ if (!user || user.disabled === true || user.deleted === true) {
60
+ api_1.logger.info(`[comms] Releasing push tokens of inactive user ${String(userId)}`);
61
+ await pushToken_1.PushToken.updateMany({ active: true, userId }, { $set: { active: false } });
62
+ return [];
63
+ }
64
+ const currentEpoch = typeof user.tokenEpoch === "number" ? user.tokenEpoch : 0;
65
+ const isCurrent = (token) => (token.tokenEpoch ?? 0) === currentEpoch;
66
+ if (tokens.every(isCurrent)) {
67
+ return tokens;
68
+ }
69
+ // A row stored without tokenEpoch counts as epoch 0.
70
+ await pushToken_1.PushToken.updateMany({
71
+ active: true,
72
+ tokenEpoch: { $nin: currentEpoch === 0 ? [0, null] : [currentEpoch] },
73
+ userId,
74
+ }, { $set: { active: false } });
75
+ return tokens.filter(isCurrent);
39
76
  }
40
77
  async recordDeliveryEvent(event) {
41
78
  const onDeliveryEvent = this.options.onDeliveryEvent;
@@ -169,7 +206,7 @@ class CommsService {
169
206
  return { channel: message.channel };
170
207
  }
171
208
  resolvePayload(context, hookErrors) {
172
- if (this.retainPayloadDays() <= 0) {
209
+ if (this.retainPayloadDays() <= 0 || this.sensitiveContexts.has(context)) {
173
210
  return undefined;
174
211
  }
175
212
  const payload = this.defaultPayload(context.message, context.channel);
@@ -446,14 +483,18 @@ class CommsService {
446
483
  async sendMail(message, sendOptions) {
447
484
  const provider = this.mailProvider();
448
485
  const hookErrors = {};
486
+ const { sensitive, ...mail } = message;
449
487
  const context = {
450
488
  attempt: 1,
451
489
  channel: "mail",
452
490
  isRetry: sendOptions?.isRetry === true,
453
- message: this.applyMailDefaults(message),
491
+ message: this.applyMailDefaults(mail),
454
492
  provider: provider.id,
455
493
  userId: sendOptions?.userId ? String(sendOptions.userId) : undefined,
456
494
  };
495
+ if (sensitive === true || sendOptions?.sensitive === true) {
496
+ this.sensitiveContexts.add(context);
497
+ }
457
498
  const before = await this.applyBeforeSend(context, hookErrors);
458
499
  const activeMessage = this.applyMailDefaults(before.message);
459
500
  context.message = activeMessage;
@@ -544,7 +585,7 @@ class CommsService {
544
585
  async sendPushToUser(message, sendOptions) {
545
586
  const provider = this.pushProvider();
546
587
  const hookErrors = {};
547
- const tokens = await pushToken_1.PushToken.find({ active: true, userId: message.userId });
588
+ const tokens = await this.deliverablePushTokens(message.userId);
548
589
  if (tokens.length === 0) {
549
590
  return [];
550
591
  }
@@ -84,6 +84,7 @@ export interface PushTokenDocument extends mongoose.Document<mongoose.Types.Obje
84
84
  lastSeenAt: Date;
85
85
  platform: PushTokenPlatform;
86
86
  token: string;
87
+ tokenEpoch?: number;
87
88
  updated: Date;
88
89
  userId: mongoose.Types.ObjectId;
89
90
  }
@@ -36,6 +36,10 @@ const pushTokenSchema = new mongoose_1.default.Schema({
36
36
  type: String,
37
37
  unique: true,
38
38
  },
39
+ tokenEpoch: {
40
+ description: "The owner's tokenEpoch when the device registered; push stops after it changes",
41
+ type: Number,
42
+ },
39
43
  userId: {
40
44
  description: "User who owns the device token",
41
45
  index: true,
@@ -22,7 +22,7 @@ const isDuplicateKeyError = (error) => error?.code === 11000;
22
22
  * A token held by another user fails the filter, and the unique index turns the resulting upsert
23
23
  * insert into a duplicate-key error that surfaces as a conflict.
24
24
  */
25
- const claimPushToken = async ({ deviceId, platform, token, userId, }) => {
25
+ const claimPushToken = async ({ deviceId, platform, token, tokenEpoch, userId, }) => {
26
26
  const now = luxon_1.DateTime.utc().toJSDate();
27
27
  const claimableFilter = {
28
28
  $or: [{ userId }, { active: false }],
@@ -37,6 +37,9 @@ const claimPushToken = async ({ deviceId, platform, token, userId, }) => {
37
37
  ...(deviceId === undefined ? {} : { deviceId }),
38
38
  lastSeenAt: now,
39
39
  platform,
40
+ // Binds the device to the session generation; a password reset or session revocation
41
+ // ends delivery until the device registers again.
42
+ tokenEpoch,
40
43
  updated: now,
41
44
  userId,
42
45
  },
@@ -87,6 +90,7 @@ const addPushTokenRoutes = (app, options) => {
87
90
  deviceId: body.deviceId,
88
91
  platform: body.platform,
89
92
  token: body.token,
93
+ tokenEpoch: typeof user.tokenEpoch === "number" ? user.tokenEpoch : 0,
90
94
  userId: user._id,
91
95
  };
92
96
  let result;
package/dist/types.d.ts CHANGED
@@ -17,6 +17,11 @@ export interface MailMessage {
17
17
  html?: string;
18
18
  metadata?: Record<string, string>;
19
19
  replyTo?: string;
20
+ /**
21
+ * The message carries a secret, such as a password-reset or email-verification link. Its
22
+ * payload is never stored in the message log. Auth recovery mail from `@terreno/api` sets it.
23
+ */
24
+ sensitive?: boolean;
20
25
  subject: string;
21
26
  templateId?: string;
22
27
  text?: string;
@@ -94,6 +99,10 @@ export interface OptOutEvent {
94
99
  reason: string;
95
100
  to: string;
96
101
  }
102
+ /** The app's user model, as far as push delivery reads it. */
103
+ export interface CommsUserModel {
104
+ findById: (id: mongoose.Types.ObjectId | string) => PromiseLike<unknown>;
105
+ }
97
106
  export interface CommsOptions {
98
107
  beforeSend?: (context: CommsHookContext) => Promise<BeforeSendResult | undefined>;
99
108
  defaultFrom?: string;
@@ -109,12 +118,20 @@ export interface CommsOptions {
109
118
  redactRecipients?: boolean;
110
119
  retainPayloadDays?: number;
111
120
  sms?: SmsProvider;
121
+ /**
122
+ * The app's user model. When set, push goes only to users that exist and are not disabled or
123
+ * deleted, and only to devices registered under the user's current `tokenEpoch`; the other
124
+ * devices are released. `CommsApp` sets it from `TerrenoApp` when omitted.
125
+ */
126
+ userModel?: CommsUserModel;
112
127
  verification?: VerificationProvider;
113
128
  }
114
129
  export interface CommsSendOptions {
115
130
  extraMetadata?: Record<string, unknown>;
116
131
  isRetry?: boolean;
117
132
  retriedFromId?: string;
133
+ /** Never store this message's payload in the log, as for `MailMessage.sensitive`. */
134
+ sensitive?: boolean;
118
135
  userId?: mongoose.Types.ObjectId | string;
119
136
  }
120
137
  export interface RetryMessageOptions {
package/package.json CHANGED
@@ -4,14 +4,14 @@
4
4
  "url": "https://github.com/TerrenoLabs/terreno/issues"
5
5
  },
6
6
  "dependencies": {
7
- "@terreno/api": "57.16.2",
7
+ "@terreno/api": "57.17.0",
8
8
  "libphonenumber-js": "^1.13.8",
9
9
  "luxon": "^3.7.2"
10
10
  },
11
11
  "description": "Pluggable mail, SMS, push, and verification providers — part of Terreno, the batteries-included TypeScript framework for universal apps.",
12
12
  "devDependencies": {
13
13
  "@biomejs/biome": "^2.3.6",
14
- "@terreno/test": "57.16.2",
14
+ "@terreno/test": "57.17.0",
15
15
  "@types/bun": "^1.4.0",
16
16
  "@types/express": "^5.0.6",
17
17
  "@types/luxon": "^3.7.1",
@@ -89,5 +89,5 @@
89
89
  "test:coverage": "bun run ../scripts/check-coverage.ts"
90
90
  },
91
91
  "types": "dist/index.d.ts",
92
- "version": "57.16.2"
92
+ "version": "57.17.0"
93
93
  }
@@ -1,4 +1,4 @@
1
- import {describe, it} from "bun:test";
1
+ import {afterEach, describe, it} from "bun:test";
2
2
  import {assert} from "chai";
3
3
  import {evaluateRetryBlock} from "../commsRetry";
4
4
  import {CommsService} from "../commsService";
@@ -204,4 +204,174 @@ describe("TwilioVerifyProvider", () => {
204
204
  assert.equal(onErrorCalls[0]?.errorClass, "config");
205
205
  assert.equal(block?.code, "comms-retry-not-retryable");
206
206
  });
207
+ describe("credentials", () => {
208
+ afterEach((): void => {
209
+ Reflect.deleteProperty(process.env, "TWILIO_ACCOUNT_SID");
210
+ Reflect.deleteProperty(process.env, "TWILIO_AUTH_TOKEN");
211
+ Reflect.deleteProperty(process.env, "TWILIO_VERIFY_SERVICE_SID");
212
+ });
213
+
214
+ it("fails fast when the account SID or auth token is missing", (): void => {
215
+ assert.throws(
216
+ (): TwilioVerifyProvider => new TwilioVerifyProvider({client: createMockClient()}),
217
+ /TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN/
218
+ );
219
+ assert.throws(
220
+ (): TwilioVerifyProvider =>
221
+ new TwilioVerifyProvider({accountSid: "ACtest", client: createMockClient()}),
222
+ /TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN/
223
+ );
224
+ });
225
+
226
+ it("reads credentials and the service SID from the environment", async (): Promise<void> => {
227
+ process.env.TWILIO_ACCOUNT_SID = "ACenv";
228
+ process.env.TWILIO_AUTH_TOKEN = "env-token";
229
+ process.env.TWILIO_VERIFY_SERVICE_SID = "VAenv";
230
+ const services: string[] = [];
231
+ const client = createMockClient();
232
+ const provider = new TwilioVerifyProvider({
233
+ client: {
234
+ verify: {
235
+ v2: {
236
+ services: (serviceSid: string) => {
237
+ services.push(serviceSid);
238
+ return client.verify.v2.services(serviceSid);
239
+ },
240
+ },
241
+ },
242
+ },
243
+ });
244
+
245
+ const result = await provider.startVerification({channel: "sms", to: "+14155552671"});
246
+
247
+ assert.deepEqual(services, ["VAenv"]);
248
+ assert.include(String(result.metadata?.consoleUrl), "/VAenv");
249
+ });
250
+ });
251
+
252
+ describe("start failure classification", () => {
253
+ const startWith = async (thrown: unknown) => {
254
+ const client: TwilioVerifyClient = {
255
+ verify: {
256
+ v2: {
257
+ services: () => ({
258
+ verificationChecks: {
259
+ create: async (): Promise<{status: string}> => ({status: "approved"}),
260
+ },
261
+ verifications: {
262
+ create: async (): Promise<{sid: string; status: string}> => {
263
+ throw thrown;
264
+ },
265
+ },
266
+ }),
267
+ },
268
+ },
269
+ };
270
+ return new TwilioVerifyProvider(providerOptions(client)).startVerification({
271
+ channel: "sms",
272
+ to: "+14155552671",
273
+ });
274
+ };
275
+
276
+ const twilioError = (fields: {
277
+ code?: number;
278
+ message?: string;
279
+ moreInfo?: string;
280
+ status?: number;
281
+ }): Error => Object.assign(new Error(fields.message ?? "Twilio failure"), fields);
282
+
283
+ it("marks invalid-destination codes as permanent failures", async (): Promise<void> => {
284
+ const result = await startWith(
285
+ twilioError({
286
+ code: 60200,
287
+ message: "Invalid parameter",
288
+ moreInfo: "https://www.twilio.com/docs/errors/60200",
289
+ status: 400,
290
+ })
291
+ );
292
+
293
+ assert.isFalse(result.accepted);
294
+ assert.equal(result.errorClass, "permanent");
295
+ assert.equal(result.errorCode, "60200");
296
+ assert.isTrue(result.isPermanentFailure);
297
+ assert.equal(result.error, "Invalid parameter");
298
+ assert.deepEqual(result.metadata?.twilioError, {
299
+ code: 60200,
300
+ message: "Invalid parameter",
301
+ moreInfo: "https://www.twilio.com/docs/errors/60200",
302
+ status: 400,
303
+ });
304
+ });
305
+
306
+ it("treats rate limits and Twilio server errors as transient", async (): Promise<void> => {
307
+ const rateLimited = await startWith(twilioError({code: 20429, status: 429}));
308
+ const throttled = await startWith(twilioError({code: 12345, status: 429}));
309
+ const unavailable = await startWith(twilioError({status: 503}));
310
+ const unknownCode = await startWith(twilioError({code: 99999, status: 400}));
311
+
312
+ assert.deepEqual(
313
+ [rateLimited, throttled, unavailable, unknownCode].map((result) => [
314
+ result.errorClass,
315
+ result.errorCode,
316
+ result.isPermanentFailure,
317
+ ]),
318
+ [
319
+ ["transient", "20429", false],
320
+ ["transient", "12345", false],
321
+ ["transient", "twilio-503", false],
322
+ ["transient", "99999", false],
323
+ ]
324
+ );
325
+ });
326
+
327
+ it("falls back to a network failure when the error has no Twilio fields", async (): Promise<void> => {
328
+ const blankMessage = await startWith(twilioError({message: ""}));
329
+ const plainObject = await startWith({message: 42});
330
+ const thrownString = await startWith("socket hang up");
331
+
332
+ assert.equal(blankMessage.errorCode, "twilio-network");
333
+ assert.equal(blankMessage.error, "");
334
+ assert.equal(plainObject.errorCode, "twilio-network");
335
+ assert.equal(plainObject.error, "Twilio Verify request failed");
336
+ assert.deepEqual(plainObject.metadata?.twilioError, {
337
+ message: "Twilio Verify request failed",
338
+ });
339
+ assert.equal(thrownString.errorClass, "transient");
340
+ assert.equal(thrownString.errorCode, "twilio-network");
341
+ assert.equal(thrownString.error, "Twilio Verify request failed");
342
+ assert.deepEqual(thrownString.metadata?.twilioError, {error: "socket hang up"});
343
+ });
344
+ });
345
+
346
+ it("reports a failed check as invalid with the Twilio message", async (): Promise<void> => {
347
+ const client: TwilioVerifyClient = {
348
+ verify: {
349
+ v2: {
350
+ services: () => ({
351
+ verificationChecks: {
352
+ create: async (): Promise<{status: string}> => {
353
+ throw Object.assign(new Error("Verification not found"), {
354
+ code: 20404,
355
+ status: 404,
356
+ });
357
+ },
358
+ },
359
+ verifications: {
360
+ create: async (): Promise<{sid: string; status: string}> => ({
361
+ sid: "VE1",
362
+ status: "pending",
363
+ }),
364
+ },
365
+ }),
366
+ },
367
+ },
368
+ };
369
+
370
+ const result = await new TwilioVerifyProvider(providerOptions(client)).checkVerification({
371
+ code: "000000",
372
+ to: "+14155552671",
373
+ });
374
+
375
+ assert.deepEqual(result, {error: "Verification not found", valid: false});
376
+ });
207
377
  });