@terreno/comms 57.3.0 → 57.6.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,86 +1,19 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __read = (this && this.__read) || function (o, n) {
50
- var m = typeof Symbol === "function" && o[Symbol.iterator];
51
- if (!m) return o;
52
- var i = m.call(o), r, ar = [], e;
53
- try {
54
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
- }
56
- catch (error) { e = { error: error }; }
57
- finally {
58
- try {
59
- if (r && !r.done && (m = i["return"])) m.call(i);
60
- }
61
- finally { if (e) throw e.error; }
62
- }
63
- return ar;
64
- };
65
2
  Object.defineProperty(exports, "__esModule", { value: true });
66
3
  exports.addPushTokenRoutes = void 0;
67
- var api_1 = require("@terreno/api");
68
- var luxon_1 = require("luxon");
69
- var pushToken_1 = require("../models/pushToken");
70
- var platformValues = ["android", "ios", "web"];
71
- var openApiOptions = function (openApi) {
72
- return openApi ? { openApi: openApi } : {};
73
- };
74
- var getAuthenticatedUser = function (req) {
75
- var user = req.user;
76
- if (!(user === null || user === void 0 ? void 0 : user._id)) {
4
+ const api_1 = require("@terreno/api");
5
+ const luxon_1 = require("luxon");
6
+ const pushToken_1 = require("../models/pushToken");
7
+ const platformValues = ["android", "ios", "web"];
8
+ const openApiOptions = (openApi) => openApi ? { openApi: openApi } : {};
9
+ const getAuthenticatedUser = (req) => {
10
+ const user = req.user;
11
+ if (!user?._id) {
77
12
  throw new api_1.APIError({ status: 401, title: "Authentication required" });
78
13
  }
79
14
  return user;
80
15
  };
81
- var isDuplicateKeyError = function (error) {
82
- return (error === null || error === void 0 ? void 0 : error.code) === 11000;
83
- };
16
+ const isDuplicateKeyError = (error) => error?.code === 11000;
84
17
  /**
85
18
  * Claims a device token for the caller in a single atomic statement.
86
19
  *
@@ -89,41 +22,39 @@ var isDuplicateKeyError = function (error) {
89
22
  * A token held by another user fails the filter, and the unique index turns the resulting upsert
90
23
  * insert into a duplicate-key error that surfaces as a conflict.
91
24
  */
92
- var claimPushToken = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
93
- var now, claimableFilter, result;
94
- var _c;
95
- var deviceId = _b.deviceId, platform = _b.platform, token = _b.token, userId = _b.userId;
96
- return __generator(this, function (_d) {
97
- switch (_d.label) {
98
- case 0:
99
- now = luxon_1.DateTime.utc().toJSDate();
100
- claimableFilter = {
101
- $or: [{ userId: userId }, { active: false }],
102
- token: token,
103
- };
104
- return [4 /*yield*/, pushToken_1.PushToken.findOneAndUpdate(claimableFilter, {
105
- // createdUpdatedPlugin only hooks save(), so timestamps are maintained here.
106
- $set: __assign(__assign({ active: true, deleted: false }, (deviceId === undefined ? {} : { deviceId: deviceId })), { lastSeenAt: now, platform: platform, updated: now, userId: userId }),
107
- $setOnInsert: { created: now },
108
- }, {
109
- includeResultMetadata: true,
110
- returnDocument: "after",
111
- runValidators: true,
112
- upsert: true,
113
- })];
114
- case 1:
115
- result = _d.sent();
116
- if (!result.value) {
117
- throw new api_1.APIError({ status: 500, title: "Push token claim returned no document" });
118
- }
119
- return [2 /*return*/, { created: ((_c = result.lastErrorObject) === null || _c === void 0 ? void 0 : _c.updatedExisting) !== true, document: result.value }];
120
- }
25
+ const claimPushToken = async ({ deviceId, platform, token, userId, }) => {
26
+ const now = luxon_1.DateTime.utc().toJSDate();
27
+ const claimableFilter = {
28
+ $or: [{ userId }, { active: false }],
29
+ token,
30
+ };
31
+ const result = await pushToken_1.PushToken.findOneAndUpdate(claimableFilter, {
32
+ // createdUpdatedPlugin only hooks save(), so timestamps are maintained here.
33
+ $set: {
34
+ active: true,
35
+ deleted: false,
36
+ // Omitting deviceId preserves a previously registered identifier on refresh.
37
+ ...(deviceId === undefined ? {} : { deviceId }),
38
+ lastSeenAt: now,
39
+ platform,
40
+ updated: now,
41
+ userId,
42
+ },
43
+ $setOnInsert: { created: now },
44
+ }, {
45
+ includeResultMetadata: true,
46
+ returnDocument: "after",
47
+ runValidators: true,
48
+ upsert: true,
121
49
  });
122
- }); };
123
- var addPushTokenRoutes = function (app, options) {
124
- var _a;
125
- var basePath = (_a = options === null || options === void 0 ? void 0 : options.basePath) !== null && _a !== void 0 ? _a : "/comms/pushTokens";
126
- var routeOpenApi = openApiOptions(options === null || options === void 0 ? void 0 : options.openApi);
50
+ if (!result.value) {
51
+ throw new api_1.APIError({ status: 500, title: "Push token claim returned no document" });
52
+ }
53
+ return { created: result.lastErrorObject?.updatedExisting !== true, document: result.value };
54
+ };
55
+ const addPushTokenRoutes = (app, options) => {
56
+ const basePath = options?.basePath ?? "/comms/pushTokens";
57
+ const routeOpenApi = openApiOptions(options?.openApi);
127
58
  // A dedicated create endpoint is required because modelRouter create cannot provide
128
59
  // the idempotent token upsert contract used by device registration.
129
60
  app.post(basePath, [
@@ -143,56 +74,43 @@ var addPushTokenRoutes = function (app, options) {
143
74
  .withResponse(200, { data: { type: "object" } })
144
75
  .withResponse(201, { data: { type: "object" } })
145
76
  .build(),
146
- ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
147
- var user, body, claim, result, error_1, retryError_1;
148
- var _a;
149
- return __generator(this, function (_b) {
150
- switch (_b.label) {
151
- case 0:
152
- user = getAuthenticatedUser(req);
153
- body = req.body;
154
- if (!((_a = body.token) === null || _a === void 0 ? void 0 : _a.trim())) {
155
- throw new api_1.APIError({ status: 400, title: "Push token is required" });
156
- }
157
- if (!body.platform || !platformValues.includes(body.platform)) {
158
- throw new api_1.APIError({ status: 400, title: "Valid push platform is required" });
159
- }
160
- claim = {
161
- deviceId: body.deviceId,
162
- platform: body.platform,
163
- token: body.token,
164
- userId: user._id,
165
- };
166
- _b.label = 1;
167
- case 1:
168
- _b.trys.push([1, 3, , 8]);
169
- return [4 /*yield*/, claimPushToken(claim)];
170
- case 2:
171
- result = _b.sent();
172
- return [3 /*break*/, 8];
173
- case 3:
174
- error_1 = _b.sent();
175
- if (!isDuplicateKeyError(error_1)) {
176
- throw error_1;
177
- }
178
- _b.label = 4;
179
- case 4:
180
- _b.trys.push([4, 6, , 7]);
181
- return [4 /*yield*/, claimPushToken(claim)];
182
- case 5:
183
- result = _b.sent();
184
- return [3 /*break*/, 7];
185
- case 6:
186
- retryError_1 = _b.sent();
187
- if (!isDuplicateKeyError(retryError_1)) {
188
- throw retryError_1;
189
- }
190
- throw new api_1.APIError({ status: 409, title: "Push token is registered to another user" });
191
- case 7: return [3 /*break*/, 8];
192
- case 8: return [2 /*return*/, res.status(result.created ? 201 : 200).json({ data: result.document })];
77
+ ], (0, api_1.asyncHandler)(async (req, res) => {
78
+ const user = getAuthenticatedUser(req);
79
+ const body = req.body;
80
+ if (!body.token?.trim()) {
81
+ throw new api_1.APIError({ status: 400, title: "Push token is required" });
82
+ }
83
+ if (!body.platform || !platformValues.includes(body.platform)) {
84
+ throw new api_1.APIError({ status: 400, title: "Valid push platform is required" });
85
+ }
86
+ const claim = {
87
+ deviceId: body.deviceId,
88
+ platform: body.platform,
89
+ token: body.token,
90
+ userId: user._id,
91
+ };
92
+ let result;
93
+ try {
94
+ result = await claimPushToken(claim);
95
+ }
96
+ catch (error) {
97
+ if (!isDuplicateKeyError(error)) {
98
+ throw error;
193
99
  }
194
- });
195
- }); }));
100
+ // A concurrent insert won the race. Retrying resolves the caller's own duplicate
101
+ // registration and leaves a genuinely foreign token failing the filter again.
102
+ try {
103
+ result = await claimPushToken(claim);
104
+ }
105
+ catch (retryError) {
106
+ if (!isDuplicateKeyError(retryError)) {
107
+ throw retryError;
108
+ }
109
+ throw new api_1.APIError({ status: 409, title: "Push token is registered to another user" });
110
+ }
111
+ }
112
+ return res.status(result.created ? 201 : 200).json({ data: result.document });
113
+ }));
196
114
  app.get(basePath, [
197
115
  (0, api_1.authenticateMiddleware)(),
198
116
  (0, api_1.createOpenApiBuilder)(routeOpenApi)
@@ -210,39 +128,31 @@ var addPushTokenRoutes = function (app, options) {
210
128
  total: { type: "number" },
211
129
  })
212
130
  .build(),
213
- ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
214
- var user, page, limit, skip, match, _a, tokens, total;
215
- return __generator(this, function (_b) {
216
- switch (_b.label) {
217
- case 0:
218
- user = getAuthenticatedUser(req);
219
- page = Math.max(1, Number.parseInt(req.query.page, 10) || 1);
220
- limit = Math.min(100, Math.max(1, Number.parseInt(req.query.limit, 10) || 20));
221
- skip = (page - 1) * limit;
222
- match = { userId: user._id };
223
- if (req.query.active === "true" || req.query.active === "false") {
224
- match.active = req.query.active === "true";
225
- }
226
- if (req.query.platform) {
227
- match.platform = req.query.platform;
228
- }
229
- return [4 /*yield*/, Promise.all([
230
- pushToken_1.PushToken.find(match).sort("-lastSeenAt").skip(skip).limit(limit),
231
- pushToken_1.PushToken.countDocuments(match),
232
- ])];
233
- case 1:
234
- _a = __read.apply(void 0, [_b.sent(), 2]), tokens = _a[0], total = _a[1];
235
- return [2 /*return*/, res.json({
236
- data: tokens,
237
- limit: limit,
238
- more: skip + limit < total,
239
- page: page,
240
- total: total,
241
- })];
242
- }
131
+ ], (0, api_1.asyncHandler)(async (req, res) => {
132
+ const user = getAuthenticatedUser(req);
133
+ const page = Math.max(1, Number.parseInt(req.query.page, 10) || 1);
134
+ const limit = Math.min(100, Math.max(1, Number.parseInt(req.query.limit, 10) || 20));
135
+ const skip = (page - 1) * limit;
136
+ const match = { userId: user._id };
137
+ if (req.query.active === "true" || req.query.active === "false") {
138
+ match.active = req.query.active === "true";
139
+ }
140
+ if (req.query.platform) {
141
+ match.platform = req.query.platform;
142
+ }
143
+ const [tokens, total] = await Promise.all([
144
+ pushToken_1.PushToken.find(match).sort("-lastSeenAt").skip(skip).limit(limit),
145
+ pushToken_1.PushToken.countDocuments(match),
146
+ ]);
147
+ return res.json({
148
+ data: tokens,
149
+ limit,
150
+ more: skip + limit < total,
151
+ page,
152
+ total,
243
153
  });
244
- }); }));
245
- app.delete("".concat(basePath, "/:id"), [
154
+ }));
155
+ app.delete(`${basePath}/:id`, [
246
156
  (0, api_1.authenticateMiddleware)(),
247
157
  (0, api_1.createOpenApiBuilder)(routeOpenApi)
248
158
  .withTags(["comms"])
@@ -250,43 +160,38 @@ var addPushTokenRoutes = function (app, options) {
250
160
  .withPathParameter("id", { type: "string" })
251
161
  .withResponse(204, {})
252
162
  .build(),
253
- ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
254
- var user, token, isOwner;
255
- return __generator(this, function (_a) {
256
- switch (_a.label) {
257
- case 0:
258
- user = getAuthenticatedUser(req);
259
- return [4 /*yield*/, pushToken_1.PushToken.findExactlyOne({ _id: req.params.id })];
260
- case 1:
261
- token = _a.sent();
262
- isOwner = token.userId.toString() === String(user._id);
263
- if (!isOwner) {
264
- throw new api_1.APIError({ status: 403, title: "Push token belongs to another user" });
265
- }
266
- token.active = false;
267
- return [4 /*yield*/, token.save()];
268
- case 2:
269
- _a.sent();
270
- return [2 /*return*/, res.status(204).send()];
271
- }
272
- });
273
- }); }));
274
- var routerOptions = __assign(__assign({}, routeOpenApi), {
163
+ ], (0, api_1.asyncHandler)(async (req, res) => {
164
+ const user = getAuthenticatedUser(req);
165
+ const token = await pushToken_1.PushToken.findExactlyOne({ _id: req.params.id });
166
+ const isOwner = token.userId.toString() === String(user._id);
167
+ if (!isOwner) {
168
+ throw new api_1.APIError({ status: 403, title: "Push token belongs to another user" });
169
+ }
170
+ token.active = false;
171
+ await token.save();
172
+ return res.status(204).send();
173
+ }));
174
+ const routerOptions = {
175
+ ...routeOpenApi,
275
176
  // Share the "comms" tag with the custom routes so generated SDK mutations invalidate this read.
276
- openApiOverwrite: { get: { tags: ["comms"] } }, permissions: {
177
+ openApiOverwrite: { get: { tags: ["comms"] } },
178
+ permissions: {
277
179
  create: [],
278
180
  delete: [],
279
181
  list: [],
280
182
  read: [api_1.Permissions.IsOwner],
281
183
  update: [],
282
- }, queryFields: ["active", "platform"],
184
+ },
185
+ queryFields: ["active", "platform"],
283
186
  // PushToken persists userId, while OwnerQueryFilter targets a persisted ownerId field.
284
- queryFilter: function (user) {
187
+ queryFilter: (user) => {
285
188
  if (!user) {
286
189
  return null;
287
190
  }
288
191
  return { userId: user.id };
289
- }, sort: "-lastSeenAt" });
192
+ },
193
+ sort: "-lastSeenAt",
194
+ };
290
195
  app.use(basePath, (0, api_1.modelRouter)(pushToken_1.PushToken, routerOptions));
291
196
  };
292
197
  exports.addPushTokenRoutes = addPushTokenRoutes;
package/dist/templates.js CHANGED
@@ -1,15 +1,4 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  Object.defineProperty(exports, "__esModule", { value: true });
14
3
  exports.renderAuthMail = exports.renderTemplate = exports.DEFAULT_AUTH_MAIL_TEMPLATES = void 0;
15
4
  exports.DEFAULT_AUTH_MAIL_TEMPLATES = {
@@ -24,42 +13,39 @@ exports.DEFAULT_AUTH_MAIL_TEMPLATES = {
24
13
  text: "Verify your email using this link: {{verifyUrl}}",
25
14
  },
26
15
  };
27
- var TEMPLATE_VARIABLE_PATTERN = /{{\s*([A-Za-z0-9_]+)\s*}}/g;
28
- var interpolate = function (value, data) {
29
- return value.replace(TEMPLATE_VARIABLE_PATTERN, function (_match, key) {
30
- if (Object.getOwnPropertyDescriptor(data, key) === undefined) {
31
- return "";
32
- }
33
- var replacement = data[key];
34
- if (replacement === null || replacement === undefined) {
35
- return "";
36
- }
37
- return String(replacement);
38
- });
39
- };
40
- var renderTemplate = function (_a) {
41
- var data = _a.data, template = _a.template;
42
- return (__assign(__assign(__assign({}, (template.html === undefined ? {} : { html: interpolate(template.html, data) })), { subject: interpolate(template.subject, data) }), (template.text === undefined ? {} : { text: interpolate(template.text, data) })));
43
- };
16
+ const TEMPLATE_VARIABLE_PATTERN = /{{\s*([A-Za-z0-9_]+)\s*}}/g;
17
+ const interpolate = (value, data) => value.replace(TEMPLATE_VARIABLE_PATTERN, (_match, key) => {
18
+ if (Object.getOwnPropertyDescriptor(data, key) === undefined) {
19
+ return "";
20
+ }
21
+ const replacement = data[key];
22
+ if (replacement === null || replacement === undefined) {
23
+ return "";
24
+ }
25
+ return String(replacement);
26
+ });
27
+ const renderTemplate = ({ data, template }) => ({
28
+ ...(template.html === undefined ? {} : { html: interpolate(template.html, data) }),
29
+ subject: interpolate(template.subject, data),
30
+ ...(template.text === undefined ? {} : { text: interpolate(template.text, data) }),
31
+ });
44
32
  exports.renderTemplate = renderTemplate;
45
- var authMailUrl = function (publicAppUrl, path, token) {
46
- var base = publicAppUrl.replace(/\/$/, "");
47
- return "".concat(base).concat(path, "?token=").concat(encodeURIComponent(token));
33
+ const authMailUrl = (publicAppUrl, path, token) => {
34
+ const base = publicAppUrl.replace(/\/$/, "");
35
+ return `${base}${path}?token=${encodeURIComponent(token)}`;
48
36
  };
49
- var renderAuthMail = function (_a) {
50
- var _b;
51
- var publicAppUrl = _a.publicAppUrl, templateId = _a.templateId, token = _a.token, templates = _a.templates;
52
- var template = (_b = templates === null || templates === void 0 ? void 0 : templates[templateId]) !== null && _b !== void 0 ? _b : exports.DEFAULT_AUTH_MAIL_TEMPLATES[templateId];
53
- var resetUrl = authMailUrl(publicAppUrl, "/resetPassword", token);
54
- var verifyUrl = authMailUrl(publicAppUrl, "/verifyEmail", token);
37
+ const renderAuthMail = ({ publicAppUrl, templateId, token, templates, }) => {
38
+ const template = templates?.[templateId] ?? exports.DEFAULT_AUTH_MAIL_TEMPLATES[templateId];
39
+ const resetUrl = authMailUrl(publicAppUrl, "/resetPassword", token);
40
+ const verifyUrl = authMailUrl(publicAppUrl, "/verifyEmail", token);
55
41
  return (0, exports.renderTemplate)({
56
42
  data: {
57
43
  publicAppUrl: publicAppUrl.replace(/\/$/, ""),
58
- resetUrl: resetUrl,
59
- token: token,
60
- verifyUrl: verifyUrl,
44
+ resetUrl,
45
+ token,
46
+ verifyUrl,
61
47
  },
62
- template: template,
48
+ template,
63
49
  });
64
50
  };
65
51
  exports.renderAuthMail = renderAuthMail;
package/dist/types.d.ts CHANGED
@@ -115,6 +115,7 @@ export interface CommsSendOptions {
115
115
  extraMetadata?: Record<string, unknown>;
116
116
  isRetry?: boolean;
117
117
  retriedFromId?: string;
118
+ userId?: mongoose.Types.ObjectId | string;
118
119
  }
119
120
  export interface RetryMessageOptions {
120
121
  messageId: string;
@@ -1,11 +1,5 @@
1
1
  import { type WebhooksApp } from "@terreno/api";
2
2
  import type { CommsService } from "../commsService";
3
- export declare const registerSendGridCommsWebhooks: ({ basePath, publicKey, service, webhooks, }: {
4
- basePath: string;
5
- publicKey: string;
6
- service: CommsService;
7
- webhooks: WebhooksApp;
8
- }) => void;
9
3
  export declare const maybeRegisterSendGridCommsWebhooks: ({ basePath, mail, service, webhooks, }: {
10
4
  basePath: string;
11
5
  mail?: {