@terreno/api 57.4.0 → 57.6.1

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 (210) hide show
  1. package/README.md +5 -5
  2. package/bunfig.toml +1 -1
  3. package/dist/actions.js +197 -368
  4. package/dist/adminModelRouter.js +88 -173
  5. package/dist/api.js +617 -852
  6. package/dist/audit/auditApp.js +48 -89
  7. package/dist/audit/auditEventModel.js +15 -16
  8. package/dist/audit/cloudTasksEnqueue.js +56 -149
  9. package/dist/audit/diff.js +70 -160
  10. package/dist/audit/processQueue.js +25 -70
  11. package/dist/audit/rbacSink.js +25 -66
  12. package/dist/audit/record.js +129 -251
  13. package/dist/auth.js +432 -681
  14. package/dist/authRecovery.js +155 -269
  15. package/dist/authTokens.js +43 -118
  16. package/dist/betterAuthApp.js +25 -26
  17. package/dist/betterAuthSetup.js +258 -413
  18. package/dist/browserLogsRoute.d.ts +6 -0
  19. package/dist/browserLogsRoute.js +97 -0
  20. package/dist/collectionRegistry.js +32 -47
  21. package/dist/config.js +53 -122
  22. package/dist/configurationApp.js +180 -361
  23. package/dist/configurationPlugin.js +130 -302
  24. package/dist/consentApp.js +276 -421
  25. package/dist/docLoader.js +78 -126
  26. package/dist/envConfigurationPlugin.js +25 -147
  27. package/dist/errors.js +151 -247
  28. package/dist/example.js +28 -34
  29. package/dist/expressServer.d.ts +10 -0
  30. package/dist/expressServer.js +109 -255
  31. package/dist/frameworkModelNames.d.ts +24 -0
  32. package/dist/frameworkModelNames.js +31 -0
  33. package/dist/githubAuth.js +152 -216
  34. package/dist/httpClient.js +176 -264
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.js +7 -2
  37. package/dist/logger.js +145 -278
  38. package/dist/mcp/auth.js +76 -128
  39. package/dist/mcp/createMCPRequest.js +4 -5
  40. package/dist/mcp/handlers.js +268 -480
  41. package/dist/mcp/query.js +56 -150
  42. package/dist/mcp/registry.js +17 -30
  43. package/dist/mcp/schemaGenerator.js +95 -181
  44. package/dist/mcp/server.js +28 -100
  45. package/dist/mcp/serviceTokens.js +102 -191
  46. package/dist/mcp/toolGenerator.js +78 -191
  47. package/dist/middleware.js +15 -27
  48. package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
  49. package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
  50. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
  51. package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
  52. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
  53. package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
  54. package/dist/migrations/generate.js +107 -229
  55. package/dist/migrations/load.js +75 -201
  56. package/dist/migrations/lock.js +54 -126
  57. package/dist/migrations/runner.js +192 -446
  58. package/dist/migrations/schemaCatalog.js +122 -263
  59. package/dist/models/consentForm.js +6 -6
  60. package/dist/models/consentResponse.js +5 -5
  61. package/dist/models/mcpServiceToken.js +66 -156
  62. package/dist/models/notification.js +6 -6
  63. package/dist/models/notificationPreference.js +6 -6
  64. package/dist/models/versionConfig.js +5 -5
  65. package/dist/notifications/notificationService.js +133 -273
  66. package/dist/notifications/notificationsApp.js +85 -179
  67. package/dist/notifications/notificationsBeforeSend.js +19 -64
  68. package/dist/notifiers/googleChatNotifier.js +36 -117
  69. package/dist/notifiers/slackNotifier.d.ts +31 -2
  70. package/dist/notifiers/slackNotifier.js +170 -119
  71. package/dist/notifiers/zoomNotifier.js +60 -111
  72. package/dist/openApi.js +107 -122
  73. package/dist/openApiBuilder.js +117 -159
  74. package/dist/openApiCompat.js +81 -148
  75. package/dist/openApiEtag.js +7 -7
  76. package/dist/openApiValidator.js +177 -286
  77. package/dist/orgs/orgContext.js +87 -157
  78. package/dist/orgs/orgPermissions.js +29 -68
  79. package/dist/orgs/orgPlugin.js +9 -27
  80. package/dist/orgs/organizationModel.js +65 -166
  81. package/dist/orgs/organizationSettings.js +29 -36
  82. package/dist/orgs/orgsApp.js +346 -608
  83. package/dist/permissions.js +88 -181
  84. package/dist/plugins.js +125 -218
  85. package/dist/populate.js +130 -240
  86. package/dist/rateLimit/applyTrustProxy.js +1 -1
  87. package/dist/rateLimit/createStore.js +7 -8
  88. package/dist/rateLimit/memoryStore.js +22 -100
  89. package/dist/rateLimit/middleware.js +48 -99
  90. package/dist/rateLimit/mongoStore.js +54 -112
  91. package/dist/rateLimit/policies.js +41 -75
  92. package/dist/rateLimit/redisStore.js +39 -133
  93. package/dist/rbac/access.js +119 -267
  94. package/dist/rbac/assertAllowed.js +95 -171
  95. package/dist/rbac/auditModel.js +14 -58
  96. package/dist/rbac/backfillAdmins.js +24 -130
  97. package/dist/rbac/fieldViews.js +46 -141
  98. package/dist/rbac/membershipOrgAdminSource.js +28 -99
  99. package/dist/rbac/middleware.js +30 -96
  100. package/dist/rbac/modelRouterAccess.js +130 -307
  101. package/dist/rbac/permissionUtils.js +40 -179
  102. package/dist/rbac/realtimeAccess.js +81 -147
  103. package/dist/rbac/resolve.d.ts +1 -1
  104. package/dist/rbac/resolve.js +148 -342
  105. package/dist/rbac/roleManager.js +318 -700
  106. package/dist/rbac/roleModel.js +44 -171
  107. package/dist/rbac/routes.js +93 -196
  108. package/dist/rbac/scopes.js +39 -133
  109. package/dist/rbac/statements.js +23 -91
  110. package/dist/rbac/userPlugin.js +3 -29
  111. package/dist/realtime/changeStreamWatcher.js +489 -800
  112. package/dist/realtime/deprecation.js +8 -10
  113. package/dist/realtime/queryMatcher.js +110 -191
  114. package/dist/realtime/queryStore.js +35 -118
  115. package/dist/realtime/realtimeApp.js +247 -401
  116. package/dist/realtime/registry.js +19 -30
  117. package/dist/realtime/sessionRevalidation.js +132 -358
  118. package/dist/realtime/socketAuth.js +89 -208
  119. package/dist/realtime/socketUser.js +10 -56
  120. package/dist/requestContext.js +93 -139
  121. package/dist/schemaMetadata.js +179 -274
  122. package/dist/scriptRunner.js +96 -266
  123. package/dist/scrubAdminFields.js +36 -108
  124. package/dist/secretProviders.js +130 -299
  125. package/dist/seedRunner.js +221 -514
  126. package/dist/sync/adminBroadcastScope.js +58 -170
  127. package/dist/sync/adminWindowAccess.js +15 -86
  128. package/dist/sync/adminWindowMutation.js +110 -181
  129. package/dist/sync/executors.js +425 -629
  130. package/dist/sync/loadHarness.js +392 -689
  131. package/dist/sync/models.js +181 -341
  132. package/dist/sync/mutationHandler.js +533 -801
  133. package/dist/sync/registrationSideEffects.js +41 -95
  134. package/dist/sync/registry.js +29 -49
  135. package/dist/sync/routes.js +484 -817
  136. package/dist/sync/scripts/compactTombstones.js +83 -228
  137. package/dist/sync/serialize.js +18 -58
  138. package/dist/sync/socketHandlers.js +253 -478
  139. package/dist/sync/streams.js +49 -117
  140. package/dist/sync/syncApp.js +12 -15
  141. package/dist/sync/syncBatch.js +63 -168
  142. package/dist/sync/syncSeqPlugin.js +430 -702
  143. package/dist/syncConsents.js +113 -253
  144. package/dist/terrenoApp.js +166 -276
  145. package/dist/tests/createTestData.js +146 -256
  146. package/dist/tests/models.js +14 -54
  147. package/dist/tests/mongoTestSetup.js +42 -103
  148. package/dist/tests/testHelper.js +31 -93
  149. package/dist/tests.js +12 -51
  150. package/dist/transformers.js +61 -164
  151. package/dist/utils.js +31 -93
  152. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  153. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  154. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  155. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  156. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  157. package/dist/versionCheckPlugin.js +52 -100
  158. package/dist/webhooks/headerValue.js +2 -2
  159. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  160. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  161. package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
  162. package/dist/webhooks/rawBody.js +1 -1
  163. package/dist/webhooks/timingSafeEqual.js +4 -5
  164. package/dist/webhooks/verifiers/hmac.js +17 -18
  165. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  166. package/dist/webhooks/verifiers/stripe.js +31 -65
  167. package/dist/webhooks/verifiers/twilio.js +23 -73
  168. package/dist/webhooks/webhooksApp.js +78 -177
  169. package/dist/zodOpenApi.js +2 -2
  170. package/package.json +6 -6
  171. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  172. package/src/api.arrayOperations.test.ts +44 -0
  173. package/src/api.ts +64 -39
  174. package/src/audit/auditApp.test.ts +5 -5
  175. package/src/audit/auditEventModel.ts +7 -3
  176. package/src/audit/auditRouter.test.ts +5 -5
  177. package/src/audit/rbacSink.test.ts +2 -2
  178. package/src/audit/record.test.ts +2 -2
  179. package/src/audit/record.ts +3 -2
  180. package/src/auth.ts +1 -1
  181. package/src/authRecovery.test.ts +43 -0
  182. package/src/authRecovery.ts +16 -10
  183. package/src/authTokens.ts +6 -2
  184. package/src/authVerification.test.ts +22 -0
  185. package/src/browserLogsRoute.ts +110 -0
  186. package/src/configurationPlugin.test.ts +1 -11
  187. package/src/expressServer.ts +10 -0
  188. package/src/frameworkModelNames.test.ts +62 -0
  189. package/src/frameworkModelNames.ts +33 -0
  190. package/src/index.ts +7 -0
  191. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  192. package/src/mcp/auth.test.ts +34 -1
  193. package/src/migrations/cli.test.ts +0 -23
  194. package/src/models/mcpServiceToken.ts +4 -3
  195. package/src/models/notification.ts +3 -2
  196. package/src/models/notificationPreference.ts +1 -1
  197. package/src/notifications/notificationsApp.test.ts +24 -1
  198. package/src/notifiers/slackNotifier.test.ts +186 -1
  199. package/src/notifiers/slackNotifier.ts +167 -8
  200. package/src/orgs/orgPlugin.ts +1 -1
  201. package/src/orgs/organizationModel.ts +11 -6
  202. package/src/plugins.test.ts +5 -0
  203. package/src/plugins.ts +3 -0
  204. package/src/realtime/realtimeApp.ts +1 -1
  205. package/src/sync/integration.test.ts +2 -2
  206. package/src/terrenoApp.ts +3 -0
  207. package/src/types.d.ts +1 -0
  208. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  209. package/tsconfig.json +13 -54
  210. package/tsconfig.typedoc.json +2 -0
package/dist/auth.js CHANGED
@@ -1,125 +1,30 @@
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 __rest = (this && this.__rest) || function (s, e) {
50
- var t = {};
51
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
52
- t[p] = s[p];
53
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
54
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
55
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
56
- t[p[i]] = s[p[i]];
57
- }
58
- return t;
59
- };
60
- var __values = (this && this.__values) || function(o) {
61
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
62
- if (m) return m.call(o);
63
- if (o && typeof o.length === "number") return {
64
- next: function () {
65
- if (o && i >= o.length) o = void 0;
66
- return { value: o && o[i++], done: !o };
67
- }
68
- };
69
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
70
- };
71
- var __read = (this && this.__read) || function (o, n) {
72
- var m = typeof Symbol === "function" && o[Symbol.iterator];
73
- if (!m) return o;
74
- var i = m.call(o), r, ar = [], e;
75
- try {
76
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
77
- }
78
- catch (error) { e = { error: error }; }
79
- finally {
80
- try {
81
- if (r && !r.done && (m = i["return"])) m.call(i);
82
- }
83
- finally { if (e) throw e.error; }
84
- }
85
- return ar;
86
- };
87
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
88
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
89
- if (ar || !(i in from)) {
90
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
91
- ar[i] = from[i];
92
- }
93
- }
94
- return to.concat(ar || Array.prototype.slice.call(from));
95
- };
96
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
97
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
98
4
  };
99
5
  Object.defineProperty(exports, "__esModule", { value: true });
100
6
  exports.addMeRoutes = exports.addAuthRoutes = exports.setupAuth = exports.generateTokens = exports.setPasswordForUser = exports.MAX_PASSWORD_LENGTH = exports.signupUser = exports.omitUserRolesFromWriteBody = exports.stripPrivilegedUserFields = exports.PRIVILEGED_USER_FIELDS = exports.authenticateMiddleware = void 0;
101
- var node_crypto_1 = require("node:crypto");
102
- var express_1 = __importDefault(require("express"));
103
- var jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
104
- var luxon_1 = require("luxon");
105
- var ms_1 = __importDefault(require("ms"));
106
- var passport_1 = __importDefault(require("passport"));
107
- var passport_anonymous_1 = require("passport-anonymous");
108
- var passport_jwt_1 = require("passport-jwt");
109
- var passport_local_1 = require("passport-local");
110
- var authRecovery_1 = require("./authRecovery");
111
- var authTokens_1 = require("./authTokens");
112
- var errors_1 = require("./errors");
113
- var logger_1 = require("./logger");
114
- var policies_1 = require("./rateLimit/policies");
115
- var requestContext_1 = require("./requestContext");
116
- var authenticateMiddleware = function (anonymous) {
117
- if (anonymous === void 0) { anonymous = false; }
118
- var strategies = ["jwt"];
7
+ const node_crypto_1 = require("node:crypto");
8
+ const express_1 = __importDefault(require("express"));
9
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
10
+ const luxon_1 = require("luxon");
11
+ const ms_1 = __importDefault(require("ms"));
12
+ const passport_1 = __importDefault(require("passport"));
13
+ const passport_anonymous_1 = require("passport-anonymous");
14
+ const passport_jwt_1 = require("passport-jwt");
15
+ const passport_local_1 = require("passport-local");
16
+ const authRecovery_1 = require("./authRecovery");
17
+ const authTokens_1 = require("./authTokens");
18
+ const errors_1 = require("./errors");
19
+ const logger_1 = require("./logger");
20
+ const policies_1 = require("./rateLimit/policies");
21
+ const requestContext_1 = require("./requestContext");
22
+ const authenticateMiddleware = (anonymous = false) => {
23
+ const strategies = ["jwt"];
119
24
  if (anonymous) {
120
25
  strategies.push("anonymous");
121
26
  }
122
- return function (req, res, next) {
27
+ return (req, res, next) => {
123
28
  if (req.user) {
124
29
  return next();
125
30
  }
@@ -131,7 +36,7 @@ var authenticateMiddleware = function (anonymous) {
131
36
  // matches on, so the response contract is unchanged.
132
37
  // (The anonymous strategy calls pass(), which skips this callback and
133
38
  // continues the chain with no user — same as before.)
134
- return passport_1.default.authenticate(strategies, { session: false }, function (err, user, info) {
39
+ return passport_1.default.authenticate(strategies, { session: false }, (err, user, info) => {
135
40
  if (err) {
136
41
  return next(err);
137
42
  }
@@ -141,7 +46,7 @@ var authenticateMiddleware = function (anonymous) {
141
46
  req.user = user;
142
47
  // req.logIn used to populate authInfo; keep that passport-public API
143
48
  // intact for downstream consumers.
144
- req.authInfo = (info !== null && info !== void 0 ? info : {});
49
+ req.authInfo = (info ?? {});
145
50
  return next();
146
51
  })(req, res, next);
147
52
  };
@@ -164,64 +69,42 @@ exports.PRIVILEGED_USER_FIELDS = [
164
69
  * Removes {@link PRIVILEGED_USER_FIELDS} from a self-service body. Fields are dropped rather
165
70
  * than rejected so clients that echo a whole user object back still succeed.
166
71
  */
167
- var stripPrivilegedUserFields = function (body, context) {
168
- var e_1, _a;
169
- var sanitized = {};
170
- var dropped = [];
171
- try {
172
- for (var _b = __values(Object.entries(body)), _c = _b.next(); !_c.done; _c = _b.next()) {
173
- var _d = __read(_c.value, 2), key = _d[0], value = _d[1];
174
- if (exports.PRIVILEGED_USER_FIELDS.includes(key)) {
175
- dropped.push(key);
176
- continue;
177
- }
178
- sanitized[key] = value;
179
- }
180
- }
181
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
182
- finally {
183
- try {
184
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
72
+ const stripPrivilegedUserFields = (body, context) => {
73
+ const sanitized = {};
74
+ const dropped = [];
75
+ for (const [key, value] of Object.entries(body)) {
76
+ if (exports.PRIVILEGED_USER_FIELDS.includes(key)) {
77
+ dropped.push(key);
78
+ continue;
185
79
  }
186
- finally { if (e_1) throw e_1.error; }
80
+ sanitized[key] = value;
187
81
  }
188
82
  if (dropped.length > 0) {
189
- logger_1.logger.warn("Ignored privileged user fields on ".concat(context, ": ").concat(dropped.join(", ")));
83
+ logger_1.logger.warn(`Ignored privileged user fields on ${context}: ${dropped.join(", ")}`);
190
84
  }
191
85
  return sanitized;
192
86
  };
193
87
  exports.stripPrivilegedUserFields = stripPrivilegedUserFields;
194
- var isEmailUpdateChangingMailbox = function (currentEmail, nextEmail) {
88
+ const isEmailUpdateChangingMailbox = (currentEmail, nextEmail) => {
195
89
  if (typeof currentEmail !== "string" || typeof nextEmail !== "string") {
196
90
  return false;
197
91
  }
198
92
  return currentEmail.trim().toLowerCase() !== nextEmail.trim().toLowerCase();
199
93
  };
200
- var omitPrivilegedFieldsFromObject = function (item, allowAdminWrite) {
201
- var e_2, _a;
94
+ const omitPrivilegedFieldsFromObject = (item, allowAdminWrite) => {
202
95
  if (!item || typeof item !== "object" || Array.isArray(item)) {
203
96
  return item;
204
97
  }
205
- var record = item;
206
- var fieldsToDrop = exports.PRIVILEGED_USER_FIELDS.filter(function (field) { return field in record && !(field === "admin" && allowAdminWrite); });
98
+ const record = item;
99
+ const fieldsToDrop = exports.PRIVILEGED_USER_FIELDS.filter((field) => field in record && !(field === "admin" && allowAdminWrite));
207
100
  if (fieldsToDrop.length === 0) {
208
101
  return item;
209
102
  }
210
- var next = __assign({}, record);
211
- try {
212
- for (var fieldsToDrop_1 = __values(fieldsToDrop), fieldsToDrop_1_1 = fieldsToDrop_1.next(); !fieldsToDrop_1_1.done; fieldsToDrop_1_1 = fieldsToDrop_1.next()) {
213
- var field = fieldsToDrop_1_1.value;
214
- Reflect.deleteProperty(next, field);
215
- }
103
+ const next = { ...record };
104
+ for (const field of fieldsToDrop) {
105
+ Reflect.deleteProperty(next, field);
216
106
  }
217
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
218
- finally {
219
- try {
220
- if (fieldsToDrop_1_1 && !fieldsToDrop_1_1.done && (_a = fieldsToDrop_1.return)) _a.call(fieldsToDrop_1);
221
- }
222
- finally { if (e_2) throw e_2.error; }
223
- }
224
- logger_1.logger.warn("Ignored privileged User fields on a modelRouter write: ".concat(fieldsToDrop.join(", ")));
107
+ logger_1.logger.warn(`Ignored privileged User fields on a modelRouter write: ${fieldsToDrop.join(", ")}`);
225
108
  return next;
226
109
  };
227
110
  /**
@@ -229,55 +112,41 @@ var omitPrivilegedFieldsFromObject = function (item, allowAdminWrite) {
229
112
  * writes on `/users`, sync, or MCP. AdminApp captures role assignments before this runs and
230
113
  * explicitly marks authorized legacy-admin writes after its additional checks.
231
114
  */
232
- var omitUserRolesFromWriteBody = function (modelName, accessControl, body, allowAdminWrite) {
233
- if (allowAdminWrite === void 0) { allowAdminWrite = false; }
115
+ const omitUserRolesFromWriteBody = (modelName, accessControl, body, allowAdminWrite = false) => {
234
116
  if (modelName !== "User" || !accessControl || body == null) {
235
117
  return body;
236
118
  }
237
119
  if (Array.isArray(body)) {
238
- return body.map(function (item) { return omitPrivilegedFieldsFromObject(item, allowAdminWrite); });
120
+ return body.map((item) => omitPrivilegedFieldsFromObject(item, allowAdminWrite));
239
121
  }
240
122
  return omitPrivilegedFieldsFromObject(body, allowAdminWrite);
241
123
  };
242
124
  exports.omitUserRolesFromWriteBody = omitUserRolesFromWriteBody;
243
- var signupUser = function (userModel, email, password, body) { return __awaiter(void 0, void 0, void 0, function () {
244
- var _a, _email, _password, rawBody, bodyRest, registrableModel, user, error_1, error_2, message;
245
- return __generator(this, function (_b) {
246
- switch (_b.label) {
247
- case 0:
248
- _a = body !== null && body !== void 0 ? body : {}, _email = _a.email, _password = _a.password, rawBody = __rest(_a, ["email", "password"]);
249
- bodyRest = (0, exports.stripPrivilegedUserFields)(rawBody, "signup");
250
- _b.label = 1;
251
- case 1:
252
- _b.trys.push([1, 8, , 9]);
253
- registrableModel = userModel;
254
- return [4 /*yield*/, registrableModel.register(__assign({ email: email }, bodyRest), password)];
255
- case 2:
256
- user = _b.sent();
257
- if (!user.postCreate) return [3 /*break*/, 6];
258
- _b.label = 3;
259
- case 3:
260
- _b.trys.push([3, 5, , 6]);
261
- return [4 /*yield*/, user.postCreate(bodyRest)];
262
- case 4:
263
- _b.sent();
264
- return [3 /*break*/, 6];
265
- case 5:
266
- error_1 = _b.sent();
267
- logger_1.logger.error("Error in user.postCreate: ".concat(error_1));
268
- throw error_1;
269
- case 6: return [4 /*yield*/, user.save()];
270
- case 7:
271
- _b.sent();
272
- return [2 /*return*/, user];
273
- case 8:
274
- error_2 = _b.sent();
275
- message = (0, errors_1.errorMessage)(error_2);
276
- throw new errors_1.APIError({ title: message });
277
- case 9: return [2 /*return*/];
125
+ const signupUser = async (userModel, email, password, body) => {
126
+ // Strip email and password from the body. They can cause mongoose to throw an error if strict is
127
+ // set.
128
+ const { email: _email, password: _password, ...rawBody } = body ?? {};
129
+ const bodyRest = (0, exports.stripPrivilegedUserFields)(rawBody, "signup");
130
+ try {
131
+ const registrableModel = userModel;
132
+ const user = await registrableModel.register({ email, ...bodyRest }, password);
133
+ if (user.postCreate) {
134
+ try {
135
+ await user.postCreate(bodyRest);
136
+ }
137
+ catch (error) {
138
+ logger_1.logger.error(`Error in user.postCreate: ${error}`);
139
+ throw error;
140
+ }
278
141
  }
279
- });
280
- }); };
142
+ await user.save();
143
+ return user;
144
+ }
145
+ catch (error) {
146
+ const message = (0, errors_1.errorMessage)(error);
147
+ throw new errors_1.APIError({ title: message });
148
+ }
149
+ };
281
150
  exports.signupUser = signupUser;
282
151
  /** Upper bound on password length accepted by {@link setPasswordForUser} (D5). */
283
152
  exports.MAX_PASSWORD_LENGTH = 256;
@@ -293,75 +162,58 @@ exports.MAX_PASSWORD_LENGTH = 256;
293
162
  * password change), logs a `logger.info` audit line with the admin id, target user id, and
294
163
  * timestamp — NEVER the password itself.
295
164
  */
296
- var setPasswordForUser = function (user_1, password_1) {
297
- var args_1 = [];
298
- for (var _i = 2; _i < arguments.length; _i++) {
299
- args_1[_i - 2] = arguments[_i];
165
+ const setPasswordForUser = async (user, password, timeoutMs = 15_000, audit) => {
166
+ if (password.length > exports.MAX_PASSWORD_LENGTH) {
167
+ throw new errors_1.APIError({
168
+ status: 400,
169
+ title: `Password must be at most ${exports.MAX_PASSWORD_LENGTH} characters`,
170
+ });
300
171
  }
301
- return __awaiter(void 0, __spreadArray([user_1, password_1], __read(args_1), false), void 0, function (user, password, timeoutMs, audit) {
302
- var targetUserId;
303
- var _a, _b;
304
- if (timeoutMs === void 0) { timeoutMs = 15000; }
305
- return __generator(this, function (_c) {
306
- switch (_c.label) {
307
- case 0:
308
- if (password.length > exports.MAX_PASSWORD_LENGTH) {
309
- throw new errors_1.APIError({
310
- status: 400,
311
- title: "Password must be at most ".concat(exports.MAX_PASSWORD_LENGTH, " characters"),
312
- });
313
- }
314
- if ((audit === null || audit === void 0 ? void 0 : audit.adminId) !== undefined) {
315
- targetUserId = (_b = (_a = user._id) !== null && _a !== void 0 ? _a : user.id) !== null && _b !== void 0 ? _b : "unknown";
316
- logger_1.logger.info("[auth] Admin ".concat(String(audit.adminId), " set password for user ").concat(String(targetUserId), " ") +
317
- "at ".concat(luxon_1.DateTime.now().toISO()));
318
- }
319
- return [4 /*yield*/, new Promise(function (resolve, reject) {
320
- var isSettled = false;
321
- var timeout = setTimeout(function () {
322
- if (isSettled) {
323
- return;
324
- }
325
- isSettled = true;
326
- reject(new Error("Timed out while setting password"));
327
- }, timeoutMs);
328
- var resolveOnce = function () {
329
- if (isSettled) {
330
- return;
331
- }
332
- isSettled = true;
333
- clearTimeout(timeout);
334
- resolve();
335
- };
336
- var rejectOnce = function (error) {
337
- if (isSettled) {
338
- return;
339
- }
340
- isSettled = true;
341
- clearTimeout(timeout);
342
- reject(error);
343
- };
344
- try {
345
- var maybePromise = user.setPassword(password, function (error) {
346
- if (error) {
347
- rejectOnce(error);
348
- return;
349
- }
350
- resolveOnce();
351
- });
352
- if (maybePromise && typeof maybePromise.then === "function") {
353
- maybePromise.then(resolveOnce).catch(rejectOnce);
354
- }
355
- }
356
- catch (error) {
357
- rejectOnce(error);
358
- }
359
- })];
360
- case 1:
361
- _c.sent();
362
- return [2 /*return*/];
172
+ if (audit?.adminId !== undefined) {
173
+ const targetUserId = user._id ?? user.id ?? "unknown";
174
+ logger_1.logger.info(`[auth] Admin ${String(audit.adminId)} set password for user ${String(targetUserId)} ` +
175
+ `at ${luxon_1.DateTime.now().toISO()}`);
176
+ }
177
+ await new Promise((resolve, reject) => {
178
+ let isSettled = false;
179
+ const timeout = setTimeout(() => {
180
+ if (isSettled) {
181
+ return;
363
182
  }
364
- });
183
+ isSettled = true;
184
+ reject(new Error("Timed out while setting password"));
185
+ }, timeoutMs);
186
+ const resolveOnce = () => {
187
+ if (isSettled) {
188
+ return;
189
+ }
190
+ isSettled = true;
191
+ clearTimeout(timeout);
192
+ resolve();
193
+ };
194
+ const rejectOnce = (error) => {
195
+ if (isSettled) {
196
+ return;
197
+ }
198
+ isSettled = true;
199
+ clearTimeout(timeout);
200
+ reject(error);
201
+ };
202
+ try {
203
+ const maybePromise = user.setPassword(password, (error) => {
204
+ if (error) {
205
+ rejectOnce(error);
206
+ return;
207
+ }
208
+ resolveOnce();
209
+ });
210
+ if (maybePromise && typeof maybePromise.then === "function") {
211
+ maybePromise.then(resolveOnce).catch(rejectOnce);
212
+ }
213
+ }
214
+ catch (error) {
215
+ rejectOnce(error);
216
+ }
365
217
  });
366
218
  };
367
219
  exports.setPasswordForUser = setPasswordForUser;
@@ -369,9 +221,9 @@ exports.setPasswordForUser = setPasswordForUser;
369
221
  * Returns the duration when `ms` can parse it, otherwise logs and returns undefined so the caller
370
222
  * keeps its default. Signing a token with an unparseable duration throws instead.
371
223
  */
372
- var validateDuration = function (envName, value) {
224
+ const validateDuration = (envName, value) => {
373
225
  if ((0, ms_1.default)(value) === undefined) {
374
- logger_1.logger.error("".concat(envName, " is not a valid duration: \"").concat(value, "\". Using the default instead."));
226
+ logger_1.logger.error(`${envName} is not a valid duration: "${value}". Using the default instead.`);
375
227
  return undefined;
376
228
  }
377
229
  return value;
@@ -393,76 +245,66 @@ var validateDuration = function (envName, value) {
393
245
  * authentication providers) to reuse and customize the same token generation logic.
394
246
  * This ensures consistent and secure token issuance across different authentication flows.
395
247
  */
396
- var generateTokens = function (user_1, authOptions_1) {
397
- var args_1 = [];
398
- for (var _i = 2; _i < arguments.length; _i++) {
399
- args_1[_i - 2] = arguments[_i];
248
+ const generateTokens = async (user, authOptions, options = {}) => {
249
+ const tokenSecretOrKey = process.env.TOKEN_SECRET;
250
+ if (!tokenSecretOrKey) {
251
+ throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set in env." });
400
252
  }
401
- return __awaiter(void 0, __spreadArray([user_1, authOptions_1], __read(args_1), false), void 0, function (user, authOptions, options) {
402
- var tokenSecretOrKey, tokenUser, sessionId, authUser, payload, tokenOptions, expiresIn, token, refreshTokenSecretOrKey, refreshToken, refreshTokenOptions, expiresIn;
403
- var _a, _b;
404
- if (options === void 0) { options = {}; }
405
- return __generator(this, function (_c) {
406
- tokenSecretOrKey = process.env.TOKEN_SECRET;
407
- if (!tokenSecretOrKey) {
408
- throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set in env." });
409
- }
410
- tokenUser = user;
411
- if (!(tokenUser === null || tokenUser === void 0 ? void 0 : tokenUser._id)) {
412
- logger_1.logger.warn("No user found for token generation");
413
- return [2 /*return*/, { refreshToken: null, token: null }];
414
- }
415
- sessionId = (_a = options.sessionId) !== null && _a !== void 0 ? _a : (0, node_crypto_1.randomUUID)();
416
- authUser = user;
417
- payload = {
418
- id: String(tokenUser._id),
419
- sid: sessionId,
420
- te: (_b = authUser.tokenEpoch) !== null && _b !== void 0 ? _b : 0,
421
- };
422
- if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateJWTPayload) {
423
- payload = __assign(__assign({}, authOptions.generateJWTPayload(authUser)), payload);
424
- }
425
- tokenOptions = {
426
- expiresIn: "15m",
427
- };
428
- if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateTokenExpiration) {
429
- tokenOptions.expiresIn = authOptions.generateTokenExpiration(authUser);
430
- }
431
- else if (process.env.TOKEN_EXPIRES_IN) {
432
- expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
433
- if (expiresIn) {
434
- tokenOptions.expiresIn = expiresIn;
435
- }
436
- }
437
- if (process.env.TOKEN_ISSUER) {
438
- tokenOptions.issuer = process.env.TOKEN_ISSUER;
439
- }
440
- token = jsonwebtoken_1.default.sign(payload, tokenSecretOrKey, tokenOptions);
441
- refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
442
- if (refreshTokenSecretOrKey) {
443
- refreshTokenOptions = {
444
- expiresIn: "30d",
445
- };
446
- if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateRefreshTokenExpiration) {
447
- refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(authUser);
448
- }
449
- else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
450
- expiresIn = validateDuration("REFRESH_TOKEN_EXPIRES_IN", process.env.REFRESH_TOKEN_EXPIRES_IN);
451
- if (expiresIn) {
452
- refreshTokenOptions.expiresIn = expiresIn;
453
- }
454
- }
455
- refreshToken = jsonwebtoken_1.default.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
456
- }
457
- else {
458
- logger_1.logger.info("REFRESH_TOKEN_SECRET not set so refresh tokens will not be issued");
253
+ const tokenUser = user;
254
+ if (!tokenUser?._id) {
255
+ logger_1.logger.warn("No user found for token generation");
256
+ return { refreshToken: null, token: null };
257
+ }
258
+ const sessionId = options.sessionId ?? (0, node_crypto_1.randomUUID)();
259
+ const authUser = user;
260
+ let payload = {
261
+ id: String(tokenUser._id),
262
+ sid: sessionId,
263
+ te: authUser.tokenEpoch ?? 0,
264
+ };
265
+ if (authOptions?.generateJWTPayload) {
266
+ payload = { ...authOptions.generateJWTPayload(authUser), ...payload };
267
+ }
268
+ const tokenOptions = {
269
+ expiresIn: "15m",
270
+ };
271
+ if (authOptions?.generateTokenExpiration) {
272
+ tokenOptions.expiresIn = authOptions.generateTokenExpiration(authUser);
273
+ }
274
+ else if (process.env.TOKEN_EXPIRES_IN) {
275
+ const expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
276
+ if (expiresIn) {
277
+ tokenOptions.expiresIn = expiresIn;
278
+ }
279
+ }
280
+ if (process.env.TOKEN_ISSUER) {
281
+ tokenOptions.issuer = process.env.TOKEN_ISSUER;
282
+ }
283
+ const token = jsonwebtoken_1.default.sign(payload, tokenSecretOrKey, tokenOptions);
284
+ const refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
285
+ let refreshToken;
286
+ if (refreshTokenSecretOrKey) {
287
+ const refreshTokenOptions = {
288
+ expiresIn: "30d",
289
+ };
290
+ if (authOptions?.generateRefreshTokenExpiration) {
291
+ refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(authUser);
292
+ }
293
+ else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
294
+ const expiresIn = validateDuration("REFRESH_TOKEN_EXPIRES_IN", process.env.REFRESH_TOKEN_EXPIRES_IN);
295
+ if (expiresIn) {
296
+ refreshTokenOptions.expiresIn = expiresIn;
459
297
  }
460
- return [2 /*return*/, { refreshToken: refreshToken, sessionId: sessionId, token: token }];
461
- });
462
- });
298
+ }
299
+ refreshToken = jsonwebtoken_1.default.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
300
+ }
301
+ else {
302
+ logger_1.logger.info("REFRESH_TOKEN_SECRET not set so refresh tokens will not be issued");
303
+ }
304
+ return { refreshToken, sessionId, token };
463
305
  };
464
306
  exports.generateTokens = generateTokens;
465
- var setupAuth = function (app, userModel) {
307
+ const setupAuth = (app, userModel) => {
466
308
  if (!userModel.createStrategy) {
467
309
  throw new errors_1.APIError({ status: 500, title: "setupAuth userModel must have .createStrategy()" });
468
310
  }
@@ -472,33 +314,21 @@ var setupAuth = function (app, userModel) {
472
314
  passReqToCallback: true,
473
315
  passwordField: "password",
474
316
  usernameField: "email",
475
- }, function (req, email, password, done) { return __awaiter(void 0, void 0, void 0, function () {
476
- var _a, _b, error_3;
477
- return __generator(this, function (_c) {
478
- switch (_c.label) {
479
- case 0:
480
- _c.trys.push([0, 2, , 3]);
481
- _a = done;
482
- _b = [undefined];
483
- return [4 /*yield*/, (0, exports.signupUser)(userModel, email, password, req.body)];
484
- case 1:
485
- _a.apply(void 0, _b.concat([_c.sent()]));
486
- return [3 /*break*/, 3];
487
- case 2:
488
- error_3 = _c.sent();
489
- return [2 /*return*/, done(error_3)];
490
- case 3: return [2 /*return*/];
491
- }
492
- });
493
- }); }));
494
- var customTokenExtractor = function (req) {
495
- var _a, _b, _c;
496
- var token = null;
497
- if ((_a = req === null || req === void 0 ? void 0 : req.cookies) === null || _a === void 0 ? void 0 : _a.jwt) {
317
+ }, async (req, email, password, done) => {
318
+ try {
319
+ done(undefined, await (0, exports.signupUser)(userModel, email, password, req.body));
320
+ }
321
+ catch (error) {
322
+ return done(error);
323
+ }
324
+ }));
325
+ const customTokenExtractor = (req) => {
326
+ let token = null;
327
+ if (req?.cookies?.jwt) {
498
328
  token = req.cookies.jwt;
499
329
  }
500
- else if ((_b = req === null || req === void 0 ? void 0 : req.headers) === null || _b === void 0 ? void 0 : _b.authorization) {
501
- token = (_c = req === null || req === void 0 ? void 0 : req.headers) === null || _c === void 0 ? void 0 : _c.authorization.split(" ")[1];
330
+ else if (req?.headers?.authorization) {
331
+ token = req?.headers?.authorization.split(" ")[1];
502
332
  }
503
333
  return token;
504
334
  };
@@ -506,243 +336,199 @@ var setupAuth = function (app, userModel) {
506
336
  if (process.env.NODE_ENV !== "test") {
507
337
  logger_1.logger.debug("Setting up JWT Authentication");
508
338
  }
509
- var secretOrKey = process.env.TOKEN_SECRET;
510
- var jwtOpts = {
339
+ const secretOrKey = process.env.TOKEN_SECRET;
340
+ const jwtOpts = {
511
341
  issuer: process.env.TOKEN_ISSUER,
512
342
  jwtFromRequest: customTokenExtractor,
513
- secretOrKey: secretOrKey,
343
+ secretOrKey,
514
344
  };
515
- passport_1.default.use("jwt", new passport_jwt_1.Strategy(jwtOpts, function (jwtPayload, done) { return __awaiter(void 0, void 0, void 0, function () {
516
- var user, error_4;
517
- return __generator(this, function (_a) {
518
- switch (_a.label) {
519
- case 0:
520
- user = null;
521
- if (!jwtPayload) {
522
- return [2 /*return*/, done(null, false)];
523
- }
524
- _a.label = 1;
525
- case 1:
526
- _a.trys.push([1, 3, , 4]);
527
- return [4 /*yield*/, userModel.findById(jwtPayload.id)];
528
- case 2:
529
- user = _a.sent();
530
- return [3 /*break*/, 4];
531
- case 3:
532
- error_4 = _a.sent();
533
- logger_1.logger.warn("[jwt] Error finding user from id: ".concat(error_4));
534
- return [2 /*return*/, done(error_4, false)];
535
- case 4:
536
- if (user) {
537
- return [2 /*return*/, done(null, user)];
538
- }
539
- if (!userModel.createAnonymousUser) return [3 /*break*/, 6];
540
- logger_1.logger.info("[jwt] Creating anonymous user");
541
- return [4 /*yield*/, userModel.createAnonymousUser()];
542
- case 5:
543
- user = _a.sent();
544
- return [2 /*return*/, done(null, user)];
545
- case 6:
546
- logger_1.logger.info("[jwt] No user found from token");
547
- return [2 /*return*/, done(null, false)];
548
- }
549
- });
550
- }); }));
345
+ passport_1.default.use("jwt", new passport_jwt_1.Strategy(jwtOpts, async (jwtPayload, done) => {
346
+ let user = null;
347
+ if (!jwtPayload) {
348
+ return done(null, false);
349
+ }
350
+ try {
351
+ user = await userModel.findById(jwtPayload.id);
352
+ }
353
+ catch (error) {
354
+ logger_1.logger.warn(`[jwt] Error finding user from id: ${error}`);
355
+ return done(error, false);
356
+ }
357
+ if (user) {
358
+ return done(null, user);
359
+ }
360
+ if (userModel.createAnonymousUser) {
361
+ logger_1.logger.info("[jwt] Creating anonymous user");
362
+ user = await userModel.createAnonymousUser();
363
+ return done(null, user);
364
+ }
365
+ logger_1.logger.info("[jwt] No user found from token");
366
+ return done(null, false);
367
+ }));
551
368
  }
552
369
  // Adds req.user to the request. This may wind up duplicating requests with passport,
553
370
  // but passport doesn't give us req.user early enough.
554
- var decodeJWTMiddleware = function (req, res, next) { return __awaiter(void 0, void 0, void 0, function () {
555
- var token, decoded, userText, expiredAt, message, details, sessionId, user, error_5;
556
- var _a, _b, _c, _d;
557
- return __generator(this, function (_e) {
558
- switch (_e.label) {
559
- case 0:
560
- if (!process.env.TOKEN_SECRET) {
561
- return [2 /*return*/, next()];
562
- }
563
- // Login, signup, and refresh exchange credentials. A stale access JWT in
564
- // Authorization / the jwt cookie must not 401 before those handlers run.
565
- if ((0, policies_1.isJwtCredentialExchangePath)(req)) {
566
- return [2 /*return*/, next()];
567
- }
568
- // Allow requests with a "Secret" prefix to pass through since this is a string value,
569
- // not a jwt that needs to be decoded
570
- if (((_b = (_a = req === null || req === void 0 ? void 0 : req.headers) === null || _a === void 0 ? void 0 : _a.authorization) === null || _b === void 0 ? void 0 : _b.split(" ")[0]) === "Secret") {
571
- return [2 /*return*/, next()];
572
- }
573
- token = customTokenExtractor(req);
574
- // For some reason, our app will happily put null into the authorization header when logging
575
- // out then back in.
576
- if (!token || token === "null" || token === "undefined") {
577
- return [2 /*return*/, next()];
578
- }
579
- try {
580
- decoded = jsonwebtoken_1.default.verify(token, process.env.TOKEN_SECRET, {
581
- issuer: process.env.TOKEN_ISSUER,
582
- });
583
- }
584
- catch (error) {
585
- // A bearer token that is not a JWT at all (e.g. a Better Auth opaque session
586
- // token) is not ours to reject — fall through so a later auth layer (Better
587
- // Auth session middleware) or the route's own permissions can handle it.
588
- // Detect this by decoding the token's header/payload structure (D1) rather
589
- // than counting dot-delimited segments: an opaque token can coincidentally
590
- // contain exactly two dots, and a malformed-but-JWT-shaped string can fail
591
- // this same check for the wrong reason — `jwt.decode` parses the actual
592
- // base64url JSON structure of each segment, which dot-counting cannot.
593
- // Genuine JWTs that fail verification (malformed/expired) still return 401 so the
594
- // client's token-refresh flow is preserved.
595
- if (jsonwebtoken_1.default.decode(token, { complete: true }) === null) {
596
- return [2 /*return*/, next()];
597
- }
598
- userText = ((_c = req.user) === null || _c === void 0 ? void 0 : _c._id) ? " for user ".concat(req.user._id, " ") : "";
599
- expiredAt = error && typeof error === "object" && "expiredAt" in error
600
- ? error.expiredAt
601
- : undefined;
602
- message = (0, errors_1.errorMessage)(error);
603
- details = "[jwt] Error decoding token".concat(userText, ": ").concat(error, ", expired at ").concat(expiredAt, ", current time: ").concat(luxon_1.DateTime.now().toMillis());
604
- logger_1.logger.debug(details);
605
- return [2 /*return*/, res.status(401).json({ details: details, message: message })];
606
- }
607
- if (!(decoded === null || decoded === void 0 ? void 0 : decoded.id)) return [3 /*break*/, 4];
608
- sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
609
- req.authTokenPayload = decoded;
610
- if (sessionId) {
611
- req.sessionId = sessionId;
612
- (0, requestContext_1.setRequestContext)({ sessionId: sessionId });
613
- }
614
- _e.label = 1;
615
- case 1:
616
- _e.trys.push([1, 3, , 4]);
617
- return [4 /*yield*/, userModel.findById(decoded.id)];
618
- case 2:
619
- user = _e.sent();
620
- req.user = user;
621
- (0, requestContext_1.updateRequestContextFromRequest)(req, res);
622
- if ((_d = req.user) === null || _d === void 0 ? void 0 : _d.disabled) {
623
- logger_1.logger.warn("[jwt] User ".concat(req.user.id, " is disabled"));
624
- return [2 /*return*/, res.status(401).json({ status: 401, title: "User is disabled" })];
625
- }
626
- return [3 /*break*/, 4];
627
- case 3:
628
- error_5 = _e.sent();
629
- logger_1.logger.warn("[jwt] Error finding user from id: ".concat(error_5));
630
- return [3 /*break*/, 4];
631
- case 4: return [2 /*return*/, next()];
371
+ const decodeJWTMiddleware = async (req, res, next) => {
372
+ if (!process.env.TOKEN_SECRET) {
373
+ return next();
374
+ }
375
+ // Login, signup, and refresh exchange credentials. A stale access JWT in
376
+ // Authorization / the jwt cookie must not 401 before those handlers run.
377
+ if ((0, policies_1.isJwtCredentialExchangePath)(req)) {
378
+ return next();
379
+ }
380
+ // Allow requests with a "Secret" prefix to pass through since this is a string value,
381
+ // not a jwt that needs to be decoded
382
+ if (req?.headers?.authorization?.split(" ")[0] === "Secret") {
383
+ return next();
384
+ }
385
+ const token = customTokenExtractor(req);
386
+ // For some reason, our app will happily put null into the authorization header when logging
387
+ // out then back in.
388
+ if (!token || token === "null" || token === "undefined") {
389
+ return next();
390
+ }
391
+ let decoded;
392
+ try {
393
+ decoded = jsonwebtoken_1.default.verify(token, process.env.TOKEN_SECRET, {
394
+ issuer: process.env.TOKEN_ISSUER,
395
+ });
396
+ }
397
+ catch (error) {
398
+ // A bearer token that is not a JWT at all (e.g. a Better Auth opaque session
399
+ // token) is not ours to reject — fall through so a later auth layer (Better
400
+ // Auth session middleware) or the route's own permissions can handle it.
401
+ // Detect this by decoding the token's header/payload structure (D1) rather
402
+ // than counting dot-delimited segments: an opaque token can coincidentally
403
+ // contain exactly two dots, and a malformed-but-JWT-shaped string can fail
404
+ // this same check for the wrong reason — `jwt.decode` parses the actual
405
+ // base64url JSON structure of each segment, which dot-counting cannot.
406
+ // Genuine JWTs that fail verification (malformed/expired) still return 401 so the
407
+ // client's token-refresh flow is preserved.
408
+ if (jsonwebtoken_1.default.decode(token, { complete: true }) === null) {
409
+ return next();
632
410
  }
633
- });
634
- }); };
411
+ const userText = req.user?._id ? ` for user ${req.user._id} ` : "";
412
+ const expiredAt = error && typeof error === "object" && "expiredAt" in error
413
+ ? error.expiredAt
414
+ : undefined;
415
+ const message = (0, errors_1.errorMessage)(error);
416
+ const details = `[jwt] Error decoding token${userText}: ${error}, expired at ${expiredAt}, current time: ${luxon_1.DateTime.now().toMillis()}`;
417
+ logger_1.logger.debug(details);
418
+ return res.status(401).json({ details, message });
419
+ }
420
+ if (decoded?.id) {
421
+ const sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
422
+ req.authTokenPayload = decoded;
423
+ if (sessionId) {
424
+ req.sessionId = sessionId;
425
+ (0, requestContext_1.setRequestContext)({ sessionId });
426
+ }
427
+ try {
428
+ const user = await userModel.findById(decoded.id);
429
+ req.user = user;
430
+ (0, requestContext_1.updateRequestContextFromRequest)(req, res);
431
+ if (req.user?.disabled) {
432
+ logger_1.logger.warn(`[jwt] User ${req.user.id} is disabled`);
433
+ return res.status(401).json({ status: 401, title: "User is disabled" });
434
+ }
435
+ }
436
+ catch (error) {
437
+ logger_1.logger.warn(`[jwt] Error finding user from id: ${error}`);
438
+ }
439
+ }
440
+ return next();
441
+ };
635
442
  app.use(decodeJWTMiddleware);
636
443
  // express 5's urlencoded() handler type doesn't match RequestHandler directly
637
444
  app.use(express_1.default.urlencoded({ extended: false }));
638
445
  };
639
446
  exports.setupAuth = setupAuth;
640
- var addAuthRoutes = function (app, userModel, authOptions) {
641
- var router = express_1.default.Router();
642
- router.post("/login", function (req, res, next) { return __awaiter(void 0, void 0, void 0, function () {
643
- return __generator(this, function (_a) {
644
- passport_1.default.authenticate("local", { session: false }, function (err, user, info) { return __awaiter(void 0, void 0, void 0, function () {
645
- var tokens;
646
- return __generator(this, function (_a) {
647
- switch (_a.label) {
648
- case 0:
649
- if (err) {
650
- logger_1.logger.error("Error logging in: ".concat(err));
651
- return [2 /*return*/, next(err)];
652
- }
653
- if (!user) {
654
- logger_1.logger.warn("Invalid login: ".concat(info));
655
- return [2 /*return*/, res.status(401).json({ message: info === null || info === void 0 ? void 0 : info.message })];
656
- }
657
- if ((authOptions === null || authOptions === void 0 ? void 0 : authOptions.requireEmailVerification) && user.emailVerified !== true) {
658
- return [2 /*return*/, next(new errors_1.APIError({
659
- code: "email-not-verified",
660
- status: 403,
661
- title: "Email is not verified",
662
- }))];
663
- }
664
- if (process.env.NODE_ENV !== "test") {
665
- logger_1.logger.info("User logged in: ".concat(user._id, ", type: ").concat(user.type || "N/A"));
666
- }
667
- return [4 /*yield*/, (0, exports.generateTokens)(user, authOptions)];
668
- case 1:
669
- tokens = _a.sent();
670
- if (tokens.sessionId) {
671
- (0, requestContext_1.setRequestContext)({ sessionId: tokens.sessionId, userId: String(user._id) });
672
- res.setHeader("X-Session-ID", tokens.sessionId);
673
- }
674
- return [2 /*return*/, res.json({
675
- data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: user === null || user === void 0 ? void 0 : user._id },
676
- })];
677
- }
447
+ const addAuthRoutes = (app, userModel, authOptions) => {
448
+ const router = express_1.default.Router();
449
+ router.post("/login", async (req, res, next) => {
450
+ passport_1.default.authenticate("local", { session: false }, async (err, user, info) => {
451
+ if (err) {
452
+ logger_1.logger.error(`Error logging in: ${err}`);
453
+ return next(err);
454
+ }
455
+ if (!user) {
456
+ logger_1.logger.warn(`Invalid login: ${info}`);
457
+ return res.status(401).json({ message: info?.message });
458
+ }
459
+ if (authOptions?.requireEmailVerification && user.emailVerified !== true) {
460
+ return next(new errors_1.APIError({
461
+ code: "email-not-verified",
462
+ status: 403,
463
+ title: "Email is not verified",
464
+ }));
465
+ }
466
+ if (process.env.NODE_ENV !== "test") {
467
+ logger_1.logger.info(`User logged in: ${user._id}, type: ${user.type || "N/A"}`);
468
+ }
469
+ const tokens = await (0, exports.generateTokens)(user, authOptions);
470
+ if (tokens.sessionId) {
471
+ (0, requestContext_1.setRequestContext)({ sessionId: tokens.sessionId, userId: String(user._id) });
472
+ res.setHeader("X-Session-ID", tokens.sessionId);
473
+ }
474
+ return res.json({
475
+ data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: user?._id },
476
+ });
477
+ })(req, res, next);
478
+ });
479
+ router.post("/refresh_token", async (req, res) => {
480
+ if (!req.body.refreshToken) {
481
+ logger_1.logger.error(`No refresh token provided, must provide refreshToken in body, user id: ${req.user?.id}`);
482
+ return res
483
+ .status(401)
484
+ .json({ message: "No refresh token provided, must provide refreshToken in body" });
485
+ }
486
+ if (!process.env.REFRESH_TOKEN_SECRET) {
487
+ logger_1.logger.error(`No REFRESH_TOKEN_SECRET set, cannot refresh token, user id: ${req.user?.id}`);
488
+ return res.status(401).json({ message: "No REFRESH_TOKEN_SECRET set, cannot refresh token" });
489
+ }
490
+ const refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
491
+ let decoded;
492
+ try {
493
+ decoded = jsonwebtoken_1.default.verify(req.body.refreshToken, refreshTokenSecretOrKey);
494
+ }
495
+ catch (error) {
496
+ logger_1.logger.error(`Error refreshing token for user ${req.user?.id}: ${error}`);
497
+ const message = (0, errors_1.errorMessage)(error);
498
+ return res.status(401).json({ message });
499
+ }
500
+ if (decoded?.id) {
501
+ const user = await userModel.findById(decoded.id);
502
+ const tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
503
+ const userEpoch = user?.tokenEpoch ?? 0;
504
+ if (!user || tokenEpoch !== userEpoch) {
505
+ logger_1.logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
506
+ return res.status(401).json({ message: "Invalid refresh token" });
507
+ }
508
+ const sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
509
+ const tokens = await (0, exports.generateTokens)(user, authOptions, { sessionId });
510
+ if (tokens.sessionId) {
511
+ (0, requestContext_1.setRequestContext)({
512
+ sessionId: tokens.sessionId,
513
+ userId: user?._id ? String(user._id) : undefined,
678
514
  });
679
- }); })(req, res, next);
680
- return [2 /*return*/];
681
- });
682
- }); });
683
- router.post("/refresh_token", function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
684
- var refreshTokenSecretOrKey, decoded, message, user, tokenEpoch, userEpoch, sessionId, tokens;
685
- var _a, _b, _c, _d, _e, _f;
686
- return __generator(this, function (_g) {
687
- switch (_g.label) {
688
- case 0:
689
- if (!req.body.refreshToken) {
690
- logger_1.logger.error("No refresh token provided, must provide refreshToken in body, user id: ".concat((_a = req.user) === null || _a === void 0 ? void 0 : _a.id));
691
- return [2 /*return*/, res
692
- .status(401)
693
- .json({ message: "No refresh token provided, must provide refreshToken in body" })];
694
- }
695
- if (!process.env.REFRESH_TOKEN_SECRET) {
696
- logger_1.logger.error("No REFRESH_TOKEN_SECRET set, cannot refresh token, user id: ".concat((_b = req.user) === null || _b === void 0 ? void 0 : _b.id));
697
- return [2 /*return*/, res.status(401).json({ message: "No REFRESH_TOKEN_SECRET set, cannot refresh token" })];
698
- }
699
- refreshTokenSecretOrKey = process.env.REFRESH_TOKEN_SECRET;
700
- try {
701
- decoded = jsonwebtoken_1.default.verify(req.body.refreshToken, refreshTokenSecretOrKey);
702
- }
703
- catch (error) {
704
- logger_1.logger.error("Error refreshing token for user ".concat((_c = req.user) === null || _c === void 0 ? void 0 : _c.id, ": ").concat(error));
705
- message = (0, errors_1.errorMessage)(error);
706
- return [2 /*return*/, res.status(401).json({ message: message })];
707
- }
708
- if (!(decoded === null || decoded === void 0 ? void 0 : decoded.id)) return [3 /*break*/, 3];
709
- return [4 /*yield*/, userModel.findById(decoded.id)];
710
- case 1:
711
- user = _g.sent();
712
- tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
713
- userEpoch = (_d = user === null || user === void 0 ? void 0 : user.tokenEpoch) !== null && _d !== void 0 ? _d : 0;
714
- if (!user || tokenEpoch !== userEpoch) {
715
- logger_1.logger.error("Invalid refresh token, user id: ".concat((_e = req.user) === null || _e === void 0 ? void 0 : _e.id));
716
- return [2 /*return*/, res.status(401).json({ message: "Invalid refresh token" })];
717
- }
718
- sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
719
- return [4 /*yield*/, (0, exports.generateTokens)(user, authOptions, { sessionId: sessionId })];
720
- case 2:
721
- tokens = _g.sent();
722
- if (tokens.sessionId) {
723
- (0, requestContext_1.setRequestContext)({
724
- sessionId: tokens.sessionId,
725
- userId: (user === null || user === void 0 ? void 0 : user._id) ? String(user._id) : undefined,
726
- });
727
- res.setHeader("X-Session-ID", tokens.sessionId);
728
- }
729
- logger_1.logger.debug("Refreshed token for ".concat(user === null || user === void 0 ? void 0 : user.id));
730
- return [2 /*return*/, res.json({ data: { refreshToken: tokens.refreshToken, token: tokens.token } })];
731
- case 3:
732
- logger_1.logger.error("Invalid refresh token, user id: ".concat((_f = req.user) === null || _f === void 0 ? void 0 : _f.id));
733
- return [2 /*return*/, res.status(401).json({ message: "Invalid refresh token" })];
515
+ res.setHeader("X-Session-ID", tokens.sessionId);
734
516
  }
735
- });
736
- }); });
737
- var signupDisabled = process.env.SIGNUP_DISABLED === "true";
517
+ logger_1.logger.debug(`Refreshed token for ${user?.id}`);
518
+ return res.json({ data: { refreshToken: tokens.refreshToken, token: tokens.token } });
519
+ }
520
+ logger_1.logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
521
+ return res.status(401).json({ message: "Invalid refresh token" });
522
+ });
523
+ const signupDisabled = process.env.SIGNUP_DISABLED === "true";
738
524
  if (!signupDisabled) {
739
525
  router.post("/signup",
740
526
  // Custom callback instead of `failWithError` — passport's internal
741
527
  // AuthenticationError is unusable in strict-mode bundles (see
742
528
  // authenticateMiddleware). Strategy errors (e.g. duplicate email) pass
743
529
  // through unchanged; a bare failure (missing credentials) is a 400.
744
- function (req, res, next) {
745
- passport_1.default.authenticate("signup", { session: false }, function (err, user) {
530
+ (req, res, next) => {
531
+ passport_1.default.authenticate("signup", { session: false }, (err, user) => {
746
532
  if (err) {
747
533
  return next(err);
748
534
  }
@@ -752,126 +538,91 @@ var addAuthRoutes = function (app, userModel, authOptions) {
752
538
  req.user = user;
753
539
  return next();
754
540
  })(req, res, next);
755
- }, function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
756
- var error_6, tokens;
757
- var _a, _b;
758
- return __generator(this, function (_c) {
759
- switch (_c.label) {
760
- case 0:
761
- if (!req.user) return [3 /*break*/, 4];
762
- _c.label = 1;
763
- case 1:
764
- _c.trys.push([1, 3, , 4]);
765
- return [4 /*yield*/, (0, authRecovery_1.sendVerificationEmail)(req.user, authOptions)];
766
- case 2:
767
- _c.sent();
768
- return [3 /*break*/, 4];
769
- case 3:
770
- error_6 = _c.sent();
771
- logger_1.logger.error("[auth] Failed to send verification mail after signup", { error: error_6 });
772
- return [3 /*break*/, 4];
773
- case 4: return [4 /*yield*/, (0, exports.generateTokens)(req.user, authOptions)];
774
- case 5:
775
- tokens = _c.sent();
776
- if (tokens.sessionId) {
777
- (0, requestContext_1.setRequestContext)({
778
- sessionId: tokens.sessionId,
779
- userId: ((_a = req.user) === null || _a === void 0 ? void 0 : _a._id) ? String(req.user._id) : undefined,
780
- });
781
- res.setHeader("X-Session-ID", tokens.sessionId);
782
- }
783
- return [2 /*return*/, res.json({
784
- data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: (_b = req.user) === null || _b === void 0 ? void 0 : _b._id },
785
- })];
541
+ }, async (req, res) => {
542
+ if (req.user && authOptions?.emailVerification !== false) {
543
+ try {
544
+ await (0, authRecovery_1.sendVerificationEmail)(req.user, authOptions);
786
545
  }
546
+ catch (error) {
547
+ logger_1.logger.error("[auth] Failed to send verification mail after signup", { error });
548
+ }
549
+ }
550
+ const tokens = await (0, exports.generateTokens)(req.user, authOptions);
551
+ if (tokens.sessionId) {
552
+ (0, requestContext_1.setRequestContext)({
553
+ sessionId: tokens.sessionId,
554
+ userId: req.user?._id ? String(req.user._id) : undefined,
555
+ });
556
+ res.setHeader("X-Session-ID", tokens.sessionId);
557
+ }
558
+ return res.json({
559
+ data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: req.user?._id },
787
560
  });
788
- }); });
561
+ });
789
562
  }
790
563
  app.set("etag", false);
791
564
  app.use("/auth", router);
792
565
  (0, authRecovery_1.addAuthRecoveryRoutes)(app, userModel, authOptions);
793
566
  };
794
567
  exports.addAuthRoutes = addAuthRoutes;
795
- var addMeRoutes = function (app, userModel, _authOptions, accessControl) {
796
- var router = express_1.default.Router();
797
- router.get("/me", (0, exports.authenticateMiddleware)(), function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
798
- var data, dataObject, withRoles, _a;
799
- var _b, _c;
800
- return __generator(this, function (_d) {
801
- switch (_d.label) {
802
- case 0:
803
- if (!((_b = req.user) === null || _b === void 0 ? void 0 : _b.id)) {
804
- logger_1.logger.debug("Not user found for /me");
805
- return [2 /*return*/, res.sendStatus(401)];
806
- }
807
- return [4 /*yield*/, userModel.findById(req.user.id)];
808
- case 1:
809
- data = _d.sent();
810
- if (!data) {
811
- logger_1.logger.debug("Not user data found for /me");
812
- return [2 /*return*/, res.sendStatus(404)];
813
- }
814
- dataObject = data.toObject();
815
- dataObject.id = data._id;
816
- if (!accessControl) return [3 /*break*/, 3];
817
- withRoles = data;
818
- dataObject.roles = (_c = withRoles.roles) !== null && _c !== void 0 ? _c : [];
819
- _a = dataObject;
820
- return [4 /*yield*/, accessControl.getPermissions({
821
- user: data,
822
- })];
823
- case 2:
824
- _a.permissions = _d.sent();
825
- _d.label = 3;
826
- case 3: return [2 /*return*/, res.json({ data: dataObject })];
827
- }
828
- });
829
- }); });
830
- router.patch("/me", (0, exports.authenticateMiddleware)(), function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
831
- var doc, update, isMailboxChange, dataObject, error_7, message;
832
- var _a, _b;
833
- return __generator(this, function (_c) {
834
- switch (_c.label) {
835
- case 0:
836
- if (!((_a = req.user) === null || _a === void 0 ? void 0 : _a.id)) {
837
- return [2 /*return*/, res.sendStatus(401)];
838
- }
839
- return [4 /*yield*/, userModel.findById(req.user.id)];
840
- case 1:
841
- doc = _c.sent();
842
- if (!doc) {
843
- return [2 /*return*/, res.sendStatus(404)];
844
- }
845
- _c.label = 2;
846
- case 2:
847
- _c.trys.push([2, 7, , 8]);
848
- update = (0, exports.stripPrivilegedUserFields)((_b = req.body) !== null && _b !== void 0 ? _b : {}, "PATCH /auth/me");
849
- isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
850
- Object.assign(doc, update);
851
- if (!isMailboxChange) return [3 /*break*/, 5];
852
- return [4 /*yield*/, authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "passwordReset")];
853
- case 3:
854
- _c.sent();
855
- if (!(userModel.schema.path("emailVerified") !== undefined)) return [3 /*break*/, 5];
568
+ const addMeRoutes = (app, userModel, _authOptions, accessControl) => {
569
+ const router = express_1.default.Router();
570
+ router.get("/me", (0, exports.authenticateMiddleware)(), async (req, res) => {
571
+ if (!req.user?.id) {
572
+ logger_1.logger.debug("Not user found for /me");
573
+ return res.sendStatus(401);
574
+ }
575
+ const data = await userModel.findById(req.user.id);
576
+ if (!data) {
577
+ logger_1.logger.debug("Not user data found for /me");
578
+ return res.sendStatus(404);
579
+ }
580
+ const dataObject = data.toObject();
581
+ dataObject.id = data._id;
582
+ if (accessControl) {
583
+ const withRoles = data;
584
+ dataObject.roles = withRoles.roles ?? [];
585
+ dataObject.permissions = await accessControl.getPermissions({
586
+ user: data,
587
+ });
588
+ }
589
+ return res.json({ data: dataObject });
590
+ });
591
+ router.patch("/me", (0, exports.authenticateMiddleware)(), async (req, res) => {
592
+ if (!req.user?.id) {
593
+ return res.sendStatus(401);
594
+ }
595
+ const doc = await userModel.findById(req.user.id);
596
+ if (!doc) {
597
+ return res.sendStatus(404);
598
+ }
599
+ // TODO support limited updates for profile.
600
+ // try {
601
+ // body = transform(req.body, "update", req.user);
602
+ // } catch (e) {
603
+ // return res.status(403).send({message: (e as Error).message});
604
+ // }
605
+ try {
606
+ const update = (0, exports.stripPrivilegedUserFields)(req.body ?? {}, "PATCH /auth/me");
607
+ const isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
608
+ Object.assign(doc, update);
609
+ if (isMailboxChange) {
610
+ await authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "passwordReset");
611
+ if (userModel.schema.path("emailVerified") !== undefined) {
856
612
  doc.emailVerified = false;
857
- return [4 /*yield*/, authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "emailVerification")];
858
- case 4:
859
- _c.sent();
860
- _c.label = 5;
861
- case 5: return [4 /*yield*/, doc.save()];
862
- case 6:
863
- _c.sent();
864
- dataObject = doc.toObject();
865
- dataObject.id = doc._id;
866
- return [2 /*return*/, res.json({ data: dataObject })];
867
- case 7:
868
- error_7 = _c.sent();
869
- message = (0, errors_1.errorMessage)(error_7);
870
- return [2 /*return*/, res.status(403).send({ message: message })];
871
- case 8: return [2 /*return*/];
613
+ await authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "emailVerification");
614
+ }
872
615
  }
873
- });
874
- }); });
616
+ await doc.save();
617
+ const dataObject = doc.toObject();
618
+ dataObject.id = doc._id;
619
+ return res.json({ data: dataObject });
620
+ }
621
+ catch (error) {
622
+ const message = (0, errors_1.errorMessage)(error);
623
+ return res.status(403).send({ message });
624
+ }
625
+ });
875
626
  app.set("etag", false);
876
627
  app.use("/auth", router);
877
628
  app.use(errors_1.apiErrorMiddleware);