@terreno/api 57.2.0 → 57.3.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.
Files changed (277) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/api.d.ts +4 -0
  4. package/dist/api.js +12 -24
  5. package/dist/auth.d.ts +23 -10
  6. package/dist/auth.js +97 -32
  7. package/dist/authRecovery.d.ts +5 -0
  8. package/dist/authRecovery.js +350 -0
  9. package/dist/authTokens.d.ts +8 -0
  10. package/dist/authTokens.js +162 -0
  11. package/dist/betterAuth.d.ts +33 -0
  12. package/dist/betterAuthApp.d.ts +4 -0
  13. package/dist/betterAuthApp.js +26 -8
  14. package/dist/betterAuthSetup.d.ts +44 -2
  15. package/dist/betterAuthSetup.js +288 -18
  16. package/dist/collectionRegistry.d.ts +38 -0
  17. package/dist/collectionRegistry.js +72 -0
  18. package/dist/configurationApp.d.ts +11 -2
  19. package/dist/configurationApp.js +2 -4
  20. package/dist/docLoader.js +35 -6
  21. package/dist/expressServer.d.ts +26 -3
  22. package/dist/expressServer.js +79 -11
  23. package/dist/index.d.ts +16 -0
  24. package/dist/index.js +38 -2
  25. package/dist/mcp/auth.d.ts +1 -0
  26. package/dist/mcp/auth.js +47 -25
  27. package/dist/mcp/handlers.d.ts +1 -1
  28. package/dist/mcp/handlers.js +67 -233
  29. package/dist/mcp/query.d.ts +2 -2
  30. package/dist/mcp/registry.d.ts +1 -5
  31. package/dist/mcp/registry.js +31 -20
  32. package/dist/mcp/schemaGenerator.d.ts +2 -7
  33. package/dist/mcp/schemaGenerator.js +41 -116
  34. package/dist/mcp/server.d.ts +1 -0
  35. package/dist/mcp/server.js +1 -0
  36. package/dist/mcp/serviceTokens.d.ts +16 -0
  37. package/dist/mcp/serviceTokens.js +345 -0
  38. package/dist/mcp/types.d.ts +2 -2
  39. package/dist/models/mcpServiceToken.d.ts +3 -0
  40. package/dist/models/mcpServiceToken.js +208 -0
  41. package/dist/openApiBuilder.d.ts +5 -4
  42. package/dist/openApiBuilder.js +61 -8
  43. package/dist/openApiCompat.js +1 -1
  44. package/dist/openApiValidator.js +0 -2
  45. package/dist/plugins.d.ts +14 -1
  46. package/dist/plugins.js +17 -6
  47. package/dist/populate.d.ts +2 -2
  48. package/dist/populate.js +47 -42
  49. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  50. package/dist/rateLimit/applyTrustProxy.js +17 -0
  51. package/dist/rateLimit/createStore.d.ts +2 -0
  52. package/dist/rateLimit/createStore.js +28 -0
  53. package/dist/rateLimit/memoryStore.d.ts +2 -0
  54. package/dist/rateLimit/memoryStore.js +108 -0
  55. package/dist/rateLimit/middleware.d.ts +11 -0
  56. package/dist/rateLimit/middleware.js +110 -0
  57. package/dist/rateLimit/mongoStore.d.ts +3 -0
  58. package/dist/rateLimit/mongoStore.js +122 -0
  59. package/dist/rateLimit/policies.d.ts +14 -0
  60. package/dist/rateLimit/policies.js +151 -0
  61. package/dist/rateLimit/redisStore.d.ts +3 -0
  62. package/dist/rateLimit/redisStore.js +155 -0
  63. package/dist/rateLimit/types.d.ts +54 -0
  64. package/dist/rateLimit/types.js +9 -0
  65. package/dist/rbac/access.js +5 -1
  66. package/dist/rbac/assertAllowed.d.ts +9 -0
  67. package/dist/rbac/assertAllowed.js +182 -0
  68. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  69. package/dist/rbac/modelRouterAccess.js +8 -4
  70. package/dist/rbac/permissionUtils.js +3 -2
  71. package/dist/rbac/resolve.js +5 -4
  72. package/dist/rbac/routes.js +15 -6
  73. package/dist/realtime/deprecation.d.ts +12 -0
  74. package/dist/realtime/deprecation.js +32 -0
  75. package/dist/realtime/realtimeApp.d.ts +1 -1
  76. package/dist/realtime/realtimeApp.js +10 -11
  77. package/dist/realtime/registry.d.ts +0 -31
  78. package/dist/realtime/registry.js +44 -31
  79. package/dist/realtime/socketAuth.d.ts +5 -5
  80. package/dist/realtime/socketAuth.js +11 -1
  81. package/dist/realtime/socketUser.d.ts +5 -1
  82. package/dist/realtime/types.d.ts +14 -4
  83. package/dist/schemaMetadata.d.ts +56 -0
  84. package/dist/schemaMetadata.js +513 -0
  85. package/dist/seedRunner.d.ts +88 -0
  86. package/dist/seedRunner.js +627 -0
  87. package/dist/sync/executors.d.ts +12 -2
  88. package/dist/sync/executors.js +8 -10
  89. package/dist/sync/loadHarness.js +28 -19
  90. package/dist/sync/models.js +26 -24
  91. package/dist/sync/mutationHandler.d.ts +9 -0
  92. package/dist/sync/mutationHandler.js +11 -6
  93. package/dist/sync/registrationSideEffects.d.ts +35 -0
  94. package/dist/sync/registrationSideEffects.js +151 -0
  95. package/dist/sync/registry.d.ts +2 -52
  96. package/dist/sync/registry.js +38 -187
  97. package/dist/sync/routes.js +3 -2
  98. package/dist/sync/scripts/compactTombstones.js +0 -2
  99. package/dist/sync/syncApp.d.ts +3 -3
  100. package/dist/sync/syncApp.js +4 -4
  101. package/dist/sync/syncBatch.js +3 -2
  102. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  103. package/dist/sync/syncSeqPlugin.js +20 -16
  104. package/dist/terrenoApp.d.ts +19 -5
  105. package/dist/terrenoApp.js +66 -18
  106. package/dist/tests/models.d.ts +2 -0
  107. package/dist/tests/models.js +6 -0
  108. package/dist/types/authToken.d.ts +33 -0
  109. package/dist/types/authToken.js +2 -0
  110. package/dist/types/mcpServiceToken.d.ts +41 -0
  111. package/dist/types/mcpServiceToken.js +2 -0
  112. package/dist/webhooks/headerValue.d.ts +2 -0
  113. package/dist/webhooks/headerValue.js +14 -0
  114. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  115. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  116. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  117. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  118. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  119. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  120. package/dist/webhooks/rawBody.d.ts +14 -0
  121. package/dist/webhooks/rawBody.js +22 -0
  122. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  123. package/dist/webhooks/timingSafeEqual.js +17 -0
  124. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  125. package/dist/webhooks/verifiers/hmac.js +49 -0
  126. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  127. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  128. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  129. package/dist/webhooks/verifiers/stripe.js +99 -0
  130. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  131. package/dist/webhooks/verifiers/twilio.js +112 -0
  132. package/dist/webhooks/webhooksApp.d.ts +33 -0
  133. package/dist/webhooks/webhooksApp.js +195 -0
  134. package/package.json +4 -5
  135. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  136. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  137. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  138. package/src/actions.ts +20 -13
  139. package/src/adminModelRouter.test.ts +133 -0
  140. package/src/api.arrayOperations.test.ts +43 -31
  141. package/src/api.hooks.test.ts +38 -29
  142. package/src/api.query.test.ts +31 -31
  143. package/src/api.test.ts +95 -96
  144. package/src/api.ts +16 -27
  145. package/src/auth.test.ts +107 -51
  146. package/src/auth.ts +98 -29
  147. package/src/authRecovery.test.ts +281 -0
  148. package/src/authRecovery.ts +279 -0
  149. package/src/authTokens.test.ts +94 -0
  150. package/src/authTokens.ts +118 -0
  151. package/src/authVerification.test.ts +293 -0
  152. package/src/betterAuth.ts +24 -0
  153. package/src/betterAuthApp.test.ts +1 -0
  154. package/src/betterAuthApp.ts +27 -9
  155. package/src/betterAuthSetup.test.ts +568 -38
  156. package/src/betterAuthSetup.ts +260 -5
  157. package/src/collectionRegistry.test.ts +165 -0
  158. package/src/collectionRegistry.ts +115 -0
  159. package/src/configurationApp.ts +13 -7
  160. package/src/docLoader.test.ts +45 -1
  161. package/src/docLoader.ts +37 -6
  162. package/src/express.d.ts +1 -0
  163. package/src/expressServer.test.ts +130 -66
  164. package/src/expressServer.ts +75 -19
  165. package/src/githubAuth.test.ts +60 -55
  166. package/src/index.ts +58 -0
  167. package/src/mcp/auth.test.ts +47 -0
  168. package/src/mcp/auth.ts +32 -11
  169. package/src/mcp/handlers.ts +45 -172
  170. package/src/mcp/integration.test.ts +59 -9
  171. package/src/mcp/query.ts +2 -4
  172. package/src/mcp/registry.ts +29 -20
  173. package/src/mcp/schemaGenerator.test.ts +8 -0
  174. package/src/mcp/schemaGenerator.ts +49 -131
  175. package/src/mcp/server.ts +2 -0
  176. package/src/mcp/serviceTokens.test.ts +330 -0
  177. package/src/mcp/serviceTokens.ts +307 -0
  178. package/src/mcp/toolGenerator.test.ts +1 -1
  179. package/src/mcp/types.ts +2 -6
  180. package/src/models/mcpServiceToken.test.ts +129 -0
  181. package/src/models/mcpServiceToken.ts +158 -0
  182. package/src/openApi.test.ts +80 -64
  183. package/src/openApiBuilder.test.ts +95 -7
  184. package/src/openApiBuilder.ts +46 -9
  185. package/src/openApiCompat.ts +1 -1
  186. package/src/openApiValidator.test.ts +49 -54
  187. package/src/openApiValidator.ts +1 -3
  188. package/src/plugins.test.ts +14 -0
  189. package/src/plugins.ts +34 -9
  190. package/src/populate.test.ts +34 -0
  191. package/src/populate.ts +40 -29
  192. package/src/rateLimit/applyTrustProxy.ts +17 -0
  193. package/src/rateLimit/createStore.ts +25 -0
  194. package/src/rateLimit/memoryStore.ts +40 -0
  195. package/src/rateLimit/middleware.ts +79 -0
  196. package/src/rateLimit/mongoStore.test.ts +80 -0
  197. package/src/rateLimit/mongoStore.ts +76 -0
  198. package/src/rateLimit/policies.ts +130 -0
  199. package/src/rateLimit/rateLimit.test.ts +328 -0
  200. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  201. package/src/rateLimit/redisStore.test.ts +114 -0
  202. package/src/rateLimit/redisStore.ts +85 -0
  203. package/src/rateLimit/types.ts +64 -0
  204. package/src/rbac/access.ts +5 -1
  205. package/src/rbac/assertAllowed.test.ts +325 -0
  206. package/src/rbac/assertAllowed.ts +157 -0
  207. package/src/rbac/backfillAdmins.test.ts +124 -0
  208. package/src/rbac/fieldViews.test.ts +89 -0
  209. package/src/rbac/modelRouterAccess.test.ts +126 -0
  210. package/src/rbac/modelRouterAccess.ts +5 -2
  211. package/src/rbac/permissionUtils.ts +3 -2
  212. package/src/rbac/realtimeAccess.test.ts +109 -1
  213. package/src/rbac/resolve.ts +5 -4
  214. package/src/rbac/roleManager.test.ts +169 -0
  215. package/src/rbac/routes.test.ts +233 -0
  216. package/src/rbac/routes.ts +16 -6
  217. package/src/realtime/deprecation.test.ts +60 -0
  218. package/src/realtime/deprecation.ts +32 -0
  219. package/src/realtime/realtime.test.ts +8 -4
  220. package/src/realtime/realtimeApp.ts +10 -11
  221. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  222. package/src/realtime/registry.ts +48 -42
  223. package/src/realtime/sessionRevalidation.test.ts +57 -44
  224. package/src/realtime/socketAuth.test.ts +75 -23
  225. package/src/realtime/socketAuth.ts +17 -6
  226. package/src/realtime/socketUser.ts +5 -3
  227. package/src/realtime/types.ts +14 -4
  228. package/src/schemaMetadata.test.ts +405 -0
  229. package/src/schemaMetadata.ts +593 -0
  230. package/src/scrubAdminFields.test.ts +105 -0
  231. package/src/seedRunner.test.ts +591 -0
  232. package/src/seedRunner.ts +464 -0
  233. package/src/sync/docMatchesMutationData.test.ts +16 -0
  234. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  235. package/src/sync/executors.test.ts +40 -0
  236. package/src/sync/executors.ts +24 -12
  237. package/src/sync/integration.test.ts +15 -7
  238. package/src/sync/loadHarness.ts +28 -19
  239. package/src/sync/models.ts +32 -18
  240. package/src/sync/mutationHandler.test.ts +16 -16
  241. package/src/sync/mutationHandler.ts +9 -7
  242. package/src/sync/registrationSideEffects.test.ts +126 -0
  243. package/src/sync/registrationSideEffects.ts +131 -0
  244. package/src/sync/registry.ts +45 -171
  245. package/src/sync/routes.ts +3 -2
  246. package/src/sync/scripts/compactTombstones.ts +0 -2
  247. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  248. package/src/sync/sync.test.ts +25 -23
  249. package/src/sync/syncApp.ts +4 -4
  250. package/src/sync/syncBatch.ts +3 -2
  251. package/src/sync/syncFrontier.test.ts +17 -15
  252. package/src/sync/syncPhaseC.test.ts +54 -43
  253. package/src/sync/syncRoutes.test.ts +51 -36
  254. package/src/sync/syncSeqPlugin.ts +66 -44
  255. package/src/sync/syncSocket.test.ts +112 -81
  256. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  257. package/src/terrenoApp.ts +87 -15
  258. package/src/tests/models.ts +14 -1
  259. package/src/types/authToken.ts +43 -0
  260. package/src/types/mcpServiceToken.ts +54 -0
  261. package/src/webhooks/headerValue.test.ts +22 -0
  262. package/src/webhooks/headerValue.ts +12 -0
  263. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  264. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  265. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  266. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  267. package/src/webhooks/rawBody.test.ts +74 -0
  268. package/src/webhooks/rawBody.ts +23 -0
  269. package/src/webhooks/timingSafeEqual.ts +16 -0
  270. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  271. package/src/webhooks/verifiers/hmac.ts +54 -0
  272. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  273. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  274. package/src/webhooks/verifiers/stripe.ts +67 -0
  275. package/src/webhooks/verifiers/twilio.ts +69 -0
  276. package/src/webhooks/webhooksApp.test.ts +221 -0
  277. package/src/webhooks/webhooksApp.ts +144 -0
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # @terreno/api
2
2
 
3
+ Styled after the Django & Django REST Framework, a batteries-include framework for building REST APIs with Node/Express/Mongoose.
4
+
3
5
  This library attempts to make creating REST APIs much easier with Express and Mongoose.
4
6
  Most REST APIs wind up being a lot of boilerplate, so this tries to cut that down without turning
5
7
  into a full blown framework of its own. This library is inspired by the
@@ -16,13 +18,13 @@ model instances.
16
18
  - **Permissions** — Fine-grained access control (IsAuthenticated, IsOwner, IsAdmin, etc.)
17
19
  - **OpenAPI** — Automatic spec generation from models and routes
18
20
  - **Logging** — Winston-based logging with scoped & feature-flagged loggers, automatic request correlation, and Google Cloud / Sentry support
19
- - **HTTP client** — Authenticated axios factory for third-party APIs with token caching, safe retries, and normalized error handling (see [Call external APIs](../docs/how-to/call-external-apis.md))
20
-
21
- ## Getting started
21
+ - **HTTP client** — Authenticated axios factory for third-party APIs with token caching, safe retries, and normalized error handling (see [Call external APIs](https://github.com/flourishhealth/terreno/blob/master/docs/how-to/call-external-apis.md))
22
22
 
23
- To install:
23
+ ## Install
24
24
 
25
- bun add @terreno/api
25
+ ```bash
26
+ bun add @terreno/api
27
+ ```
26
28
 
27
29
  ## DateOnly Type
28
30
 
@@ -165,7 +167,7 @@ setupServer({
165
167
  });
166
168
  ```
167
169
 
168
- **Learn more:** See the [GitHub OAuth how-to guide](../docs/how-to/add-github-oauth.md) for complete setup instructions.
170
+ **Learn more:** See the [GitHub OAuth how-to guide](https://github.com/flourishhealth/terreno/blob/master/docs/how-to/add-github-oauth.md) for complete setup instructions.
169
171
 
170
172
  ## Logging
171
173
 
@@ -217,7 +219,7 @@ In production, pass a structured transport (e.g. `@google-cloud/logging-winston`
217
219
  `loggingOptions`/`setupLogging` so the correlation fields and labels reach Log Explorer as
218
220
  `jsonPayload`.
219
221
 
220
- **Learn more:** See the [Logging & Tracing reference](../docs/reference/api.md#logging--tracing) for
222
+ **Learn more:** See the [Logging & Tracing reference](https://github.com/flourishhealth/terreno/blob/master/docs/reference/api.md#logging--tracing) for
221
223
  the full API, label conventions, and Google Cloud Logging / Sentry details.
222
224
 
223
225
  ## Sentry
@@ -288,3 +290,11 @@ A lot of dev may require using bun link. You'll want to keep the `bun run dev` w
288
290
  bun link
289
291
  cd $your-api-repo
290
292
  bun link @terreno/api
293
+
294
+ ## Documentation
295
+
296
+ Full API reference: [docs/reference/api.md](https://github.com/flourishhealth/terreno/blob/master/docs/reference/api.md)
297
+
298
+ ## License and Contributing
299
+
300
+ Licensed under the [MIT License](https://github.com/flourishhealth/terreno/blob/master/LICENSE). See [CONTRIBUTING.md](https://github.com/flourishhealth/terreno/blob/master/CONTRIBUTING.md) for contribution guidelines.
package/dist/actions.js CHANGED
@@ -338,23 +338,32 @@ var getArrayFieldNames = function (model) {
338
338
  .filter(function (config) { return config.instance === "Array"; })
339
339
  .map(function (config) { return config.path; });
340
340
  };
341
- // Registration-time validation throws plain Error so misconfiguration fails at app boot.
341
+ // Registration-time validation throws APIError so misconfiguration fails at app boot.
342
342
  var validateActionConfig = function (scope, name, config) {
343
343
  if (!name) {
344
- throw new Error("Action name cannot be empty");
344
+ throw new errors_1.APIError({ status: 500, title: "Action name cannot be empty" });
345
345
  }
346
346
  if (!exports.ACTION_NAME_PATTERN.test(name)) {
347
- throw new Error("Invalid action name \"".concat(name, "\". Action names must match ").concat(exports.ACTION_NAME_PATTERN.toString()));
347
+ throw new errors_1.APIError({
348
+ status: 500,
349
+ title: "Invalid action name \"".concat(name, "\". Action names must match ").concat(exports.ACTION_NAME_PATTERN.toString()),
350
+ });
348
351
  }
349
352
  if (config.permissions === undefined && !config.access) {
350
- throw new Error("Action \"".concat(name, "\" (").concat(scope, ") is missing required \"permissions\" or \"access\". ") +
351
- "Provide at least one permission function, an access descriptor, or [] to disable the action.");
353
+ throw new errors_1.APIError({
354
+ status: 500,
355
+ title: "Action \"".concat(name, "\" (").concat(scope, ") is missing required \"permissions\" or \"access\". ") +
356
+ "Provide at least one permission function, an access descriptor, or [] to disable the action.",
357
+ });
352
358
  }
353
359
  if (config.permissions !== undefined && config.permissions.length === 0 && !config.access) {
354
360
  return;
355
361
  }
356
362
  if (config.method !== "GET" && config.method !== "POST") {
357
- throw new Error("Action \"".concat(name, "\" (").concat(scope, ") only supports GET and POST methods"));
363
+ throw new errors_1.APIError({
364
+ status: 500,
365
+ title: "Action \"".concat(name, "\" (").concat(scope, ") only supports GET and POST methods"),
366
+ });
358
367
  }
359
368
  };
360
369
  var assertNoActionCollisions = function (model, options) {
@@ -369,7 +378,10 @@ var assertNoActionCollisions = function (model, options) {
369
378
  var _d = __read(_c.value, 2), name_1 = _d[0], config = _d[1];
370
379
  validateActionConfig(scope, name_1, config);
371
380
  if (scope === "instance" && arrayFields.has(name_1)) {
372
- throw new Error("instanceAction '".concat(name_1, "' collides with array field operations on /:id/").concat(name_1));
381
+ throw new errors_1.APIError({
382
+ status: 500,
383
+ title: "instanceAction '".concat(name_1, "' collides with array field operations on /:id/").concat(name_1),
384
+ });
373
385
  }
374
386
  }
375
387
  }
package/dist/api.d.ts CHANGED
@@ -281,6 +281,10 @@ export interface ModelRouterOptions<T> {
281
281
  * through the RealtimeApp plugin's change stream watcher.
282
282
  *
283
283
  * Requires the RealtimeApp plugin to be registered with TerrenoApp.
284
+ *
285
+ * @deprecated Removed in Terreno 58. Use `sync` with
286
+ * `@terreno/syncdb` instead. `RealtimeApp` remains required for sync sockets.
287
+ * See docs/how-to/migrate-rtk-to-syncdb.md.
284
288
  */
285
289
  realtime?: RealtimeConfig;
286
290
  /**
package/dist/api.js CHANGED
@@ -134,6 +134,7 @@ var mongoose_1 = __importDefault(require("mongoose"));
134
134
  var actions_1 = require("./actions");
135
135
  var adminModelRouter_1 = require("./adminModelRouter");
136
136
  var auth_1 = require("./auth");
137
+ var collectionRegistry_1 = require("./collectionRegistry");
137
138
  var errors_1 = require("./errors");
138
139
  var logger_1 = require("./logger");
139
140
  var registry_1 = require("./mcp/registry");
@@ -141,9 +142,8 @@ var openApi_1 = require("./openApi");
141
142
  var openApiValidator_1 = require("./openApiValidator");
142
143
  var permissions_1 = require("./permissions");
143
144
  var modelRouterAccess_1 = require("./rbac/modelRouterAccess");
144
- var registry_2 = require("./realtime/registry");
145
+ var deprecation_1 = require("./realtime/deprecation");
145
146
  var executors_1 = require("./sync/executors");
146
- var registry_3 = require("./sync/registry");
147
147
  var transformers_1 = require("./transformers");
148
148
  var utils_1 = require("./utils");
149
149
  var addPopulateToQuery = function (
@@ -400,27 +400,17 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
400
400
  model = pathOrModel;
401
401
  options = modelOrOptions;
402
402
  }
403
- // Register MCP before building so _buildModelRouter can replace options
404
- // with RBAC-resolved permissions (access+accessControl is not deferred).
405
- if (options.mcp) {
403
+ // Pathless MCP only — when a route path is present, registerCollection below
404
+ // owns the catalog entry and MCP shares that routePath key.
405
+ if (options.mcp && path === undefined) {
406
406
  (0, registry_1.registerMCPModel)(model, options.mcp, options);
407
407
  }
408
408
  var shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
409
409
  if (path !== undefined) {
410
- // Register before building so _buildModelRouter can replace options with
411
- // RBAC-resolved permissions (same contract as MCP).
412
410
  if (options.realtime) {
413
- (0, registry_2.registerRealtime)({
414
- collectionName: model.collection.collectionName,
415
- config: options.realtime,
416
- modelName: model.modelName,
417
- options: options,
418
- routePath: path,
419
- });
420
- }
421
- if (options.sync) {
422
- (0, registry_3.registerSync)({ config: options.sync, model: model, options: options, routePath: path });
411
+ (0, deprecation_1.warnRealtimeDeprecated)(model.modelName, path);
423
412
  }
413
+ (0, collectionRegistry_1.registerCollection)({ model: model, options: options, routePath: path });
424
414
  }
425
415
  var router = shouldDeferBuild ? express_1.default.Router() : _buildModelRouter(model, options, path);
426
416
  if (path !== undefined) {
@@ -430,9 +420,7 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
430
420
  var _a;
431
421
  var enrichedOptions = (0, adminModelRouter_1.enrichModelRouterOptions)(model, __assign(__assign({}, options), { openApi: context.openApi }), context);
432
422
  var runtimeOptions = __assign(__assign({}, enrichedOptions), { accessControl: (_a = enrichedOptions.accessControl) !== null && _a !== void 0 ? _a : context.accessControl });
433
- if (options.realtime) {
434
- (0, registry_2.updateRealtimeRegistryOptions)(path, runtimeOptions);
435
- }
423
+ (0, collectionRegistry_1.replaceCollectionOptions)(path, runtimeOptions);
436
424
  return _buildModelRouter(model, runtimeOptions, path);
437
425
  },
438
426
  model: model,
@@ -442,6 +430,7 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
442
430
  };
443
431
  }
444
432
  if (options.realtime) {
433
+ (0, deprecation_1.warnRealtimeDeprecated)(model.modelName);
445
434
  logger_1.logger.warn("modelRouter for ".concat(model.modelName, " has realtime config but was called without a path. ") +
446
435
  "Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)");
447
436
  }
@@ -463,12 +452,12 @@ var _buildModelRouter = function (model, options, routePath) {
463
452
  scope: (_a = options.access) === null || _a === void 0 ? void 0 : _a.scope,
464
453
  });
465
454
  options = __assign(__assign({}, options), { permissions: resolvedAccess.permissions, queryFilter: ((_b = resolvedAccess.queryFilter) !== null && _b !== void 0 ? _b : options.queryFilter), responseHandler: ((_d = (_c = resolvedAccess.responseHandler) !== null && _c !== void 0 ? _c : options.responseHandler) !== null && _d !== void 0 ? _d : transformers_1.defaultResponseHandler) });
455
+ if (routePath) {
456
+ (0, collectionRegistry_1.replaceCollectionOptions)(routePath, options);
457
+ }
466
458
  if (options.mcp) {
467
459
  (0, registry_1.updateMCPRegistryOptions)(model.modelName, options);
468
460
  }
469
- if (options.sync && routePath) {
470
- (0, registry_3.updateSyncRegistryOptions)(routePath, options);
471
- }
472
461
  (0, actions_1.assertNoActionCollisions)(model, options);
473
462
  (0, actions_1.registerActionRoutes)(router, model, options);
474
463
  // User endpoints run after actions; actions win on path conflicts.
@@ -515,7 +504,6 @@ var _buildModelRouter = function (model, options, routePath) {
515
504
  }
516
505
  });
517
506
  }); }));
518
- // TODO add rate limit
519
507
  router.get("/", [
520
508
  (0, auth_1.authenticateMiddleware)(options.allowAnonymous),
521
509
  (0, permissions_1.permissionMiddleware)(model, options),
package/dist/auth.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import express from "express";
2
- import type { Model, ObjectId } from "mongoose";
2
+ import type { Model, ObjectId, Query } from "mongoose";
3
+ import passport from "passport";
3
4
  import type { AuthOptions } from "./expressServer";
4
5
  export interface User {
5
6
  _id: ObjectId | string;
@@ -10,25 +11,34 @@ export interface User {
10
11
  * This can be helpful for pre-signup users.
11
12
  */
12
13
  isAnonymous?: boolean;
14
+ /** Login identifier; present on passport-local and Better Auth app users. */
15
+ email?: string;
16
+ /** Incremented on password reset so outstanding refresh tokens fail. */
17
+ tokenEpoch?: number;
18
+ /** Set by emailVerificationPlugin; login may require this when requireEmailVerification is on. */
19
+ emailVerified?: boolean;
13
20
  }
14
21
  export interface UserModel extends Model<User> {
15
22
  createAnonymousUser?: (id?: string) => Promise<User>;
16
23
  postCreate?: (body: Record<string, unknown>) => Promise<void>;
17
- createStrategy(): any;
18
- serializeUser(): any;
19
- deserializeUser(): any;
20
- findByUsername(username: string, findOpts: any): any;
24
+ createStrategy(): passport.Strategy;
25
+ serializeUser(): (user: User, cb: (err: unknown, id?: unknown) => void) => void;
26
+ deserializeUser(): (username: string, cb: (err: unknown, user?: User | null) => void) => void;
27
+ findByUsername(username: string, findOpts: boolean | {
28
+ selectHashSaltFields?: boolean;
29
+ }): Query<User | null, User>;
21
30
  }
22
31
  export interface GenerateTokensOptions {
23
32
  sessionId?: string;
24
33
  }
25
34
  export declare const authenticateMiddleware: (anonymous?: boolean) => (req: express.Request, res: express.Response, next: express.NextFunction) => any;
26
35
  /**
27
- * User fields that confer authority. Self-service requests (anonymous signup, `PATCH /me`)
28
- * must never set them, or any caller could grant themselves admin or an RBAC role. Elevate
29
- * users through the admin API or `access.roles.assign` instead.
36
+ * User fields that confer authority or skip security gates. Self-service requests
37
+ * (anonymous signup, `PATCH /me`) must never set them, or any caller could grant
38
+ * themselves admin, an RBAC role, a verified email, or a reset epoch. Elevate users
39
+ * through the admin API or `access.roles.assign` instead.
30
40
  */
31
- export declare const PRIVILEGED_USER_FIELDS: readonly ["admin", "roles", "organizationIds"];
41
+ export declare const PRIVILEGED_USER_FIELDS: readonly ["admin", "roles", "organizationIds", "emailVerified", "tokenEpoch"];
32
42
  /**
33
43
  * Removes {@link PRIVILEGED_USER_FIELDS} from a self-service body. Fields are dropped rather
34
44
  * than rejected so clients that echo a whole user object back still succeed.
@@ -40,7 +50,10 @@ export declare const stripPrivilegedUserFields: (body: Record<string, unknown>,
40
50
  * explicitly marks authorized legacy-admin writes after its additional checks.
41
51
  */
42
52
  export declare const omitUserRolesFromWriteBody: (modelName: string, accessControl: unknown, body: unknown, allowAdminWrite?: boolean) => unknown;
43
- export declare const signupUser: (userModel: UserModel, email: string, password: string, body?: Record<string, unknown>) => Promise<any>;
53
+ export declare const signupUser: (userModel: UserModel, email: string, password: string, body?: Record<string, unknown>) => Promise<User & {
54
+ postCreate?: (body: Record<string, unknown>) => Promise<void>;
55
+ save: () => Promise<unknown>;
56
+ }>;
44
57
  /** A user document exposing passport-local-mongoose's `setPassword`. */
45
58
  export interface HasSetPassword {
46
59
  _id?: unknown;
package/dist/auth.js CHANGED
@@ -107,8 +107,11 @@ var passport_1 = __importDefault(require("passport"));
107
107
  var passport_anonymous_1 = require("passport-anonymous");
108
108
  var passport_jwt_1 = require("passport-jwt");
109
109
  var passport_local_1 = require("passport-local");
110
+ var authRecovery_1 = require("./authRecovery");
111
+ var authTokens_1 = require("./authTokens");
110
112
  var errors_1 = require("./errors");
111
113
  var logger_1 = require("./logger");
114
+ var policies_1 = require("./rateLimit/policies");
112
115
  var requestContext_1 = require("./requestContext");
113
116
  var authenticateMiddleware = function (anonymous) {
114
117
  if (anonymous === void 0) { anonymous = false; }
@@ -145,11 +148,18 @@ var authenticateMiddleware = function (anonymous) {
145
148
  };
146
149
  exports.authenticateMiddleware = authenticateMiddleware;
147
150
  /**
148
- * User fields that confer authority. Self-service requests (anonymous signup, `PATCH /me`)
149
- * must never set them, or any caller could grant themselves admin or an RBAC role. Elevate
150
- * users through the admin API or `access.roles.assign` instead.
151
+ * User fields that confer authority or skip security gates. Self-service requests
152
+ * (anonymous signup, `PATCH /me`) must never set them, or any caller could grant
153
+ * themselves admin, an RBAC role, a verified email, or a reset epoch. Elevate users
154
+ * through the admin API or `access.roles.assign` instead.
151
155
  */
152
- exports.PRIVILEGED_USER_FIELDS = ["admin", "roles", "organizationIds"];
156
+ exports.PRIVILEGED_USER_FIELDS = [
157
+ "admin",
158
+ "roles",
159
+ "organizationIds",
160
+ "emailVerified",
161
+ "tokenEpoch",
162
+ ];
153
163
  /**
154
164
  * Removes {@link PRIVILEGED_USER_FIELDS} from a self-service body. Fields are dropped rather
155
165
  * than rejected so clients that echo a whole user object back still succeed.
@@ -181,6 +191,12 @@ var stripPrivilegedUserFields = function (body, context) {
181
191
  return sanitized;
182
192
  };
183
193
  exports.stripPrivilegedUserFields = stripPrivilegedUserFields;
194
+ var isEmailUpdateChangingMailbox = function (currentEmail, nextEmail) {
195
+ if (typeof currentEmail !== "string" || typeof nextEmail !== "string") {
196
+ return false;
197
+ }
198
+ return currentEmail.trim().toLowerCase() !== nextEmail.trim().toLowerCase();
199
+ };
184
200
  var omitPrivilegedFieldsFromObject = function (item, allowAdminWrite) {
185
201
  var e_2, _a;
186
202
  if (!item || typeof item !== "object" || Array.isArray(item)) {
@@ -225,7 +241,7 @@ var omitUserRolesFromWriteBody = function (modelName, accessControl, body, allow
225
241
  };
226
242
  exports.omitUserRolesFromWriteBody = omitUserRolesFromWriteBody;
227
243
  var signupUser = function (userModel, email, password, body) { return __awaiter(void 0, void 0, void 0, function () {
228
- var _a, _email, _password, rawBody, bodyRest, user, error_1, error_2, message;
244
+ var _a, _email, _password, rawBody, bodyRest, registrableModel, user, error_1, error_2, message;
229
245
  return __generator(this, function (_b) {
230
246
  switch (_b.label) {
231
247
  case 0:
@@ -234,7 +250,8 @@ var signupUser = function (userModel, email, password, body) { return __awaiter(
234
250
  _b.label = 1;
235
251
  case 1:
236
252
  _b.trys.push([1, 8, , 9]);
237
- return [4 /*yield*/, userModel.register(__assign({ email: email }, bodyRest), password)];
253
+ registrableModel = userModel;
254
+ return [4 /*yield*/, registrableModel.register(__assign({ email: email }, bodyRest), password)];
238
255
  case 2:
239
256
  user = _b.sent();
240
257
  if (!user.postCreate) return [3 /*break*/, 6];
@@ -382,10 +399,10 @@ var generateTokens = function (user_1, authOptions_1) {
382
399
  args_1[_i - 2] = arguments[_i];
383
400
  }
384
401
  return __awaiter(void 0, __spreadArray([user_1, authOptions_1], __read(args_1), false), void 0, function (user, authOptions, options) {
385
- var tokenSecretOrKey, tokenUser, sessionId, payload, tokenOptions, expiresIn, token, refreshTokenSecretOrKey, refreshToken, refreshTokenOptions, expiresIn;
386
- var _a;
402
+ var tokenSecretOrKey, tokenUser, sessionId, authUser, payload, tokenOptions, expiresIn, token, refreshTokenSecretOrKey, refreshToken, refreshTokenOptions, expiresIn;
403
+ var _a, _b;
387
404
  if (options === void 0) { options = {}; }
388
- return __generator(this, function (_b) {
405
+ return __generator(this, function (_c) {
389
406
  tokenSecretOrKey = process.env.TOKEN_SECRET;
390
407
  if (!tokenSecretOrKey) {
391
408
  throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set in env." });
@@ -396,15 +413,20 @@ var generateTokens = function (user_1, authOptions_1) {
396
413
  return [2 /*return*/, { refreshToken: null, token: null }];
397
414
  }
398
415
  sessionId = (_a = options.sessionId) !== null && _a !== void 0 ? _a : (0, node_crypto_1.randomUUID)();
399
- payload = { id: String(tokenUser._id), sid: sessionId };
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
+ };
400
422
  if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateJWTPayload) {
401
- payload = __assign(__assign({}, authOptions.generateJWTPayload(user)), payload);
423
+ payload = __assign(__assign({}, authOptions.generateJWTPayload(authUser)), payload);
402
424
  }
403
425
  tokenOptions = {
404
426
  expiresIn: "15m",
405
427
  };
406
428
  if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateTokenExpiration) {
407
- tokenOptions.expiresIn = authOptions.generateTokenExpiration(user);
429
+ tokenOptions.expiresIn = authOptions.generateTokenExpiration(authUser);
408
430
  }
409
431
  else if (process.env.TOKEN_EXPIRES_IN) {
410
432
  expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
@@ -422,7 +444,7 @@ var generateTokens = function (user_1, authOptions_1) {
422
444
  expiresIn: "30d",
423
445
  };
424
446
  if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.generateRefreshTokenExpiration) {
425
- refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(user);
447
+ refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(authUser);
426
448
  }
427
449
  else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
428
450
  expiresIn = validateDuration("REFRESH_TOKEN_EXPIRES_IN", process.env.REFRESH_TOKEN_EXPIRES_IN);
@@ -538,6 +560,11 @@ var setupAuth = function (app, userModel) {
538
560
  if (!process.env.TOKEN_SECRET) {
539
561
  return [2 /*return*/, next()];
540
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
+ }
541
568
  // Allow requests with a "Secret" prefix to pass through since this is a string value,
542
569
  // not a jwt that needs to be decoded
543
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") {
@@ -606,8 +633,7 @@ var setupAuth = function (app, userModel) {
606
633
  });
607
634
  }); };
608
635
  app.use(decodeJWTMiddleware);
609
- // noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
610
- // biome-ignore lint/suspicious/noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
636
+ // express 5's urlencoded() handler type doesn't match RequestHandler directly
611
637
  app.use(express_1.default.urlencoded({ extended: false }));
612
638
  };
613
639
  exports.setupAuth = setupAuth;
@@ -628,6 +654,13 @@ var addAuthRoutes = function (app, userModel, authOptions) {
628
654
  logger_1.logger.warn("Invalid login: ".concat(info));
629
655
  return [2 /*return*/, res.status(401).json({ message: info === null || info === void 0 ? void 0 : info.message })];
630
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
+ }
631
664
  if (process.env.NODE_ENV !== "test") {
632
665
  logger_1.logger.info("User logged in: ".concat(user._id, ", type: ").concat(user.type || "N/A"));
633
666
  }
@@ -648,10 +681,10 @@ var addAuthRoutes = function (app, userModel, authOptions) {
648
681
  });
649
682
  }); });
650
683
  router.post("/refresh_token", function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
651
- var refreshTokenSecretOrKey, decoded, message, user, sessionId, tokens;
652
- var _a, _b, _c, _d;
653
- return __generator(this, function (_e) {
654
- switch (_e.label) {
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) {
655
688
  case 0:
656
689
  if (!req.body.refreshToken) {
657
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));
@@ -675,11 +708,17 @@ var addAuthRoutes = function (app, userModel, authOptions) {
675
708
  if (!(decoded === null || decoded === void 0 ? void 0 : decoded.id)) return [3 /*break*/, 3];
676
709
  return [4 /*yield*/, userModel.findById(decoded.id)];
677
710
  case 1:
678
- user = _e.sent();
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
+ }
679
718
  sessionId = (0, requestContext_1.getSessionIdFromJwtPayload)(decoded);
680
719
  return [4 /*yield*/, (0, exports.generateTokens)(user, authOptions, { sessionId: sessionId })];
681
720
  case 2:
682
- tokens = _e.sent();
721
+ tokens = _g.sent();
683
722
  if (tokens.sessionId) {
684
723
  (0, requestContext_1.setRequestContext)({
685
724
  sessionId: tokens.sessionId,
@@ -690,7 +729,7 @@ var addAuthRoutes = function (app, userModel, authOptions) {
690
729
  logger_1.logger.debug("Refreshed token for ".concat(user === null || user === void 0 ? void 0 : user.id));
691
730
  return [2 /*return*/, res.json({ data: { refreshToken: tokens.refreshToken, token: tokens.token } })];
692
731
  case 3:
693
- logger_1.logger.error("Invalid refresh token, user id: ".concat((_d = req.user) === null || _d === void 0 ? void 0 : _d.id));
732
+ logger_1.logger.error("Invalid refresh token, user id: ".concat((_f = req.user) === null || _f === void 0 ? void 0 : _f.id));
694
733
  return [2 /*return*/, res.status(401).json({ message: "Invalid refresh token" })];
695
734
  }
696
735
  });
@@ -714,12 +753,25 @@ var addAuthRoutes = function (app, userModel, authOptions) {
714
753
  return next();
715
754
  })(req, res, next);
716
755
  }, function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
717
- var tokens;
756
+ var error_6, tokens;
718
757
  var _a, _b;
719
758
  return __generator(this, function (_c) {
720
759
  switch (_c.label) {
721
- case 0: return [4 /*yield*/, (0, exports.generateTokens)(req.user, authOptions)];
760
+ case 0:
761
+ if (!req.user) return [3 /*break*/, 4];
762
+ _c.label = 1;
722
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:
723
775
  tokens = _c.sent();
724
776
  if (tokens.sessionId) {
725
777
  (0, requestContext_1.setRequestContext)({
@@ -737,6 +789,7 @@ var addAuthRoutes = function (app, userModel, authOptions) {
737
789
  }
738
790
  app.set("etag", false);
739
791
  app.use("/auth", router);
792
+ (0, authRecovery_1.addAuthRecoveryRoutes)(app, userModel, authOptions);
740
793
  };
741
794
  exports.addAuthRoutes = addAuthRoutes;
742
795
  var addMeRoutes = function (app, userModel, _authOptions, accessControl) {
@@ -775,7 +828,7 @@ var addMeRoutes = function (app, userModel, _authOptions, accessControl) {
775
828
  });
776
829
  }); });
777
830
  router.patch("/me", (0, exports.authenticateMiddleware)(), function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
778
- var doc, dataObject, error_6, message;
831
+ var doc, update, isMailboxChange, dataObject, error_7, message;
779
832
  var _a, _b;
780
833
  return __generator(this, function (_c) {
781
834
  switch (_c.label) {
@@ -791,19 +844,31 @@ var addMeRoutes = function (app, userModel, _authOptions, accessControl) {
791
844
  }
792
845
  _c.label = 2;
793
846
  case 2:
794
- _c.trys.push([2, 4, , 5]);
795
- Object.assign(doc, (0, exports.stripPrivilegedUserFields)((_b = req.body) !== null && _b !== void 0 ? _b : {}, "PATCH /auth/me"));
796
- return [4 /*yield*/, doc.save()];
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")];
797
853
  case 3:
854
+ _c.sent();
855
+ if (!(userModel.schema.path("emailVerified") !== undefined)) return [3 /*break*/, 5];
856
+ 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:
798
863
  _c.sent();
799
864
  dataObject = doc.toObject();
800
865
  dataObject.id = doc._id;
801
866
  return [2 /*return*/, res.json({ data: dataObject })];
802
- case 4:
803
- error_6 = _c.sent();
804
- message = (0, errors_1.errorMessage)(error_6);
867
+ case 7:
868
+ error_7 = _c.sent();
869
+ message = (0, errors_1.errorMessage)(error_7);
805
870
  return [2 /*return*/, res.status(403).send({ message: message })];
806
- case 5: return [2 /*return*/];
871
+ case 8: return [2 /*return*/];
807
872
  }
808
873
  });
809
874
  }); });
@@ -0,0 +1,5 @@
1
+ import express from "express";
2
+ import { type User, type UserModel } from "./auth";
3
+ import type { AuthOptions } from "./expressServer";
4
+ export declare const sendVerificationEmail: (user: User, authOptions?: AuthOptions) => Promise<void>;
5
+ export declare const addAuthRecoveryRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions) => void;