@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.
@@ -11,7 +11,7 @@ import {
11
11
  import {evaluateRetryBlock, throwRetryBlock} from "./commsRetry";
12
12
  import {CommsMessage} from "./models/commsMessage";
13
13
  import {PushToken} from "./models/pushToken";
14
- import type {CommsMessageAttempt, CommsMessageDocument} from "./modelTypes";
14
+ import type {CommsMessageAttempt, CommsMessageDocument, PushTokenDocument} from "./modelTypes";
15
15
  import type {
16
16
  CheckVerificationOptions,
17
17
  CommsChannel,
@@ -20,6 +20,7 @@ import type {
20
20
  CommsMessageStatus,
21
21
  CommsOptions,
22
22
  CommsSendOptions,
23
+ CommsUserModel,
23
24
  DeliveryEvent,
24
25
  MailMessage,
25
26
  MailProvider,
@@ -68,8 +69,58 @@ export class CommsService {
68
69
  private readonly consoleSms = new ConsoleSmsProvider();
69
70
  private readonly consoleVerification = new ConsoleVerificationProvider();
70
71
 
72
+ private userModel: CommsUserModel | undefined;
73
+ // Sends whose payload carries a secret; their log rows keep no payload.
74
+ private readonly sensitiveContexts = new WeakSet<CommsHookContext>();
75
+
71
76
  constructor(options?: CommsOptions) {
72
77
  this.options = options ?? {};
78
+ this.userModel = this.options.userModel;
79
+ }
80
+
81
+ /** Set the user model push delivery checks, unless one was passed in the options. */
82
+ setUserModel(userModel: CommsUserModel | undefined): void {
83
+ this.userModel = this.options.userModel ?? userModel;
84
+ }
85
+
86
+ /**
87
+ * The user's devices that may receive push: none for a missing, disabled, or deleted user, and
88
+ * only those registered under the user's current tokenEpoch, so a password reset or session
89
+ * revocation ends delivery to devices bound before it. The rest are released.
90
+ */
91
+ private async deliverablePushTokens(
92
+ userId: mongoose.Types.ObjectId | string
93
+ ): Promise<PushTokenDocument[]> {
94
+ const tokens = await PushToken.find({active: true, userId});
95
+ if (!this.userModel || tokens.length === 0) {
96
+ return tokens;
97
+ }
98
+ const user = (await this.userModel.findById(userId)) as {
99
+ deleted?: unknown;
100
+ disabled?: unknown;
101
+ tokenEpoch?: unknown;
102
+ } | null;
103
+ if (!user || user.disabled === true || user.deleted === true) {
104
+ logger.info(`[comms] Releasing push tokens of inactive user ${String(userId)}`);
105
+ await PushToken.updateMany({active: true, userId}, {$set: {active: false}});
106
+ return [];
107
+ }
108
+ const currentEpoch = typeof user.tokenEpoch === "number" ? user.tokenEpoch : 0;
109
+ const isCurrent = (token: PushTokenDocument): boolean =>
110
+ (token.tokenEpoch ?? 0) === currentEpoch;
111
+ if (tokens.every(isCurrent)) {
112
+ return tokens;
113
+ }
114
+ // A row stored without tokenEpoch counts as epoch 0.
115
+ await PushToken.updateMany(
116
+ {
117
+ active: true,
118
+ tokenEpoch: {$nin: currentEpoch === 0 ? [0, null] : [currentEpoch]},
119
+ userId,
120
+ },
121
+ {$set: {active: false}}
122
+ );
123
+ return tokens.filter(isCurrent);
73
124
  }
74
125
 
75
126
  async recordDeliveryEvent(event: DeliveryEvent): Promise<void> {
@@ -223,7 +274,7 @@ export class CommsService {
223
274
  }
224
275
 
225
276
  private resolvePayload(context: CommsHookContext, hookErrors: Record<string, string[]>): unknown {
226
- if (this.retainPayloadDays() <= 0) {
277
+ if (this.retainPayloadDays() <= 0 || this.sensitiveContexts.has(context)) {
227
278
  return undefined;
228
279
  }
229
280
  const payload = this.defaultPayload(context.message, context.channel);
@@ -626,14 +677,18 @@ export class CommsService {
626
677
  async sendMail(message: MailMessage, sendOptions?: CommsSendOptions): Promise<SendResult> {
627
678
  const provider = this.mailProvider();
628
679
  const hookErrors: Record<string, string[]> = {};
680
+ const {sensitive, ...mail} = message;
629
681
  const context: CommsHookContext = {
630
682
  attempt: 1,
631
683
  channel: "mail",
632
684
  isRetry: sendOptions?.isRetry === true,
633
- message: this.applyMailDefaults(message),
685
+ message: this.applyMailDefaults(mail),
634
686
  provider: provider.id,
635
687
  userId: sendOptions?.userId ? String(sendOptions.userId) : undefined,
636
688
  };
689
+ if (sensitive === true || sendOptions?.sensitive === true) {
690
+ this.sensitiveContexts.add(context);
691
+ }
637
692
  const before = await this.applyBeforeSend(context, hookErrors);
638
693
  const activeMessage = this.applyMailDefaults(before.message as MailMessage);
639
694
  context.message = activeMessage;
@@ -731,7 +786,7 @@ export class CommsService {
731
786
  ): Promise<SendResult[]> {
732
787
  const provider = this.pushProvider();
733
788
  const hookErrors: Record<string, string[]> = {};
734
- const tokens = await PushToken.find({active: true, userId: message.userId});
789
+ const tokens = await this.deliverablePushTokens(message.userId);
735
790
  if (tokens.length === 0) {
736
791
  return [];
737
792
  }
package/src/modelTypes.ts CHANGED
@@ -106,6 +106,7 @@ export interface PushTokenDocument
106
106
  lastSeenAt: Date;
107
107
  platform: PushTokenPlatform;
108
108
  token: string;
109
+ tokenEpoch?: number;
109
110
  updated: Date;
110
111
  userId: mongoose.Types.ObjectId;
111
112
  }
@@ -40,6 +40,10 @@ const pushTokenSchema: PushTokenSchema = new mongoose.Schema<PushTokenDocument,
40
40
  type: String,
41
41
  unique: true,
42
42
  },
43
+ tokenEpoch: {
44
+ description: "The owner's tokenEpoch when the device registered; push stops after it changes",
45
+ type: Number,
46
+ },
43
47
  userId: {
44
48
  description: "User who owns the device token",
45
49
  index: true,
@@ -30,14 +30,19 @@ const platformValues: PushTokenPlatform[] = ["android", "ios", "web"];
30
30
  const openApiOptions = (openApi?: unknown): {openApi?: OpenApiMiddleware} =>
31
31
  openApi ? {openApi: openApi as OpenApiMiddleware} : {};
32
32
 
33
- const getAuthenticatedUser = (
34
- req: express.Request
35
- ): {_id: unknown; admin?: boolean; id?: string} => {
36
- const user = req.user as {_id?: unknown; admin?: boolean; id?: string} | undefined;
33
+ interface AuthenticatedUser {
34
+ _id: unknown;
35
+ admin?: boolean;
36
+ id?: string;
37
+ tokenEpoch?: number;
38
+ }
39
+
40
+ const getAuthenticatedUser = (req: express.Request): AuthenticatedUser => {
41
+ const user = req.user as Partial<AuthenticatedUser> | undefined;
37
42
  if (!user?._id) {
38
43
  throw new APIError({status: 401, title: "Authentication required"});
39
44
  }
40
- return user as {_id: unknown; admin?: boolean; id?: string};
45
+ return user as AuthenticatedUser;
41
46
  };
42
47
 
43
48
  const isDuplicateKeyError = (error: unknown): boolean =>
@@ -55,11 +60,13 @@ const claimPushToken = async ({
55
60
  deviceId,
56
61
  platform,
57
62
  token,
63
+ tokenEpoch,
58
64
  userId,
59
65
  }: {
60
66
  deviceId?: string;
61
67
  platform: PushTokenPlatform;
62
68
  token: string;
69
+ tokenEpoch: number;
63
70
  userId: Types.ObjectId;
64
71
  }): Promise<{created: boolean; document: PushTokenDocument}> => {
65
72
  const now = DateTime.utc().toJSDate();
@@ -78,6 +85,9 @@ const claimPushToken = async ({
78
85
  ...(deviceId === undefined ? {} : {deviceId}),
79
86
  lastSeenAt: now,
80
87
  platform,
88
+ // Binds the device to the session generation; a password reset or session revocation
89
+ // ends delivery until the device registers again.
90
+ tokenEpoch,
81
91
  updated: now,
82
92
  userId,
83
93
  },
@@ -140,6 +150,7 @@ export const addPushTokenRoutes = (
140
150
  deviceId: body.deviceId,
141
151
  platform: body.platform,
142
152
  token: body.token,
153
+ tokenEpoch: typeof user.tokenEpoch === "number" ? user.tokenEpoch : 0,
143
154
  userId: user._id as Types.ObjectId,
144
155
  };
145
156
 
package/src/types.ts CHANGED
@@ -20,6 +20,11 @@ export interface MailMessage {
20
20
  html?: string;
21
21
  metadata?: Record<string, string>;
22
22
  replyTo?: string;
23
+ /**
24
+ * The message carries a secret, such as a password-reset or email-verification link. Its
25
+ * payload is never stored in the message log. Auth recovery mail from `@terreno/api` sets it.
26
+ */
27
+ sensitive?: boolean;
23
28
  subject: string;
24
29
  templateId?: string;
25
30
  text?: string;
@@ -113,6 +118,11 @@ export interface OptOutEvent {
113
118
  to: string;
114
119
  }
115
120
 
121
+ /** The app's user model, as far as push delivery reads it. */
122
+ export interface CommsUserModel {
123
+ findById: (id: mongoose.Types.ObjectId | string) => PromiseLike<unknown>;
124
+ }
125
+
116
126
  export interface CommsOptions {
117
127
  beforeSend?: (context: CommsHookContext) => Promise<BeforeSendResult | undefined>;
118
128
  defaultFrom?: string;
@@ -128,6 +138,12 @@ export interface CommsOptions {
128
138
  redactRecipients?: boolean;
129
139
  retainPayloadDays?: number;
130
140
  sms?: SmsProvider;
141
+ /**
142
+ * The app's user model. When set, push goes only to users that exist and are not disabled or
143
+ * deleted, and only to devices registered under the user's current `tokenEpoch`; the other
144
+ * devices are released. `CommsApp` sets it from `TerrenoApp` when omitted.
145
+ */
146
+ userModel?: CommsUserModel;
131
147
  verification?: VerificationProvider;
132
148
  }
133
149
 
@@ -135,6 +151,8 @@ export interface CommsSendOptions {
135
151
  extraMetadata?: Record<string, unknown>;
136
152
  isRetry?: boolean;
137
153
  retriedFromId?: string;
154
+ /** Never store this message's payload in the log, as for `MailMessage.sensitive`. */
155
+ sensitive?: boolean;
138
156
  userId?: mongoose.Types.ObjectId | string;
139
157
  }
140
158