@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/src/auth.test.ts CHANGED
@@ -1,5 +1,3 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {afterEach, beforeEach, describe, expect, it, setSystemTime, spyOn} from "bun:test";
4
2
  import {assert} from "chai";
5
3
  import express from "express";
@@ -37,7 +35,7 @@ const decodeTokenPayload = <T extends Record<string, unknown>>(token: string): T
37
35
 
38
36
  describe("auth tests", () => {
39
37
  let app: express.Application;
40
- let admin: any;
38
+ let admin: Awaited<ReturnType<typeof setupDb>>[number];
41
39
  let contextEvents: Array<{
42
40
  currentSessionId?: string;
43
41
  requestId?: string;
@@ -148,7 +146,7 @@ describe("auth tests", () => {
148
146
  app = new TerrenoApp({
149
147
  configureApp: addRoutes,
150
148
  skipListen: true,
151
- userModel: UserModel as any,
149
+ userModel: UserModel as unknown as AuthUserModel,
152
150
  }).build();
153
151
  agent = supertest.agent(app);
154
152
  });
@@ -212,7 +210,7 @@ describe("auth tests", () => {
212
210
  const getRes = await agent.get("/food").expect(200);
213
211
 
214
212
  expect(getRes.body.data).toHaveLength(4);
215
- expect(getRes.body.data.find((f: any) => f.name === "Peas")).toBeDefined();
213
+ expect(getRes.body.data.find((f: Food) => f.name === "Peas")).toBeDefined();
216
214
 
217
215
  const updateRes = await agent
218
216
  .patch(`/food/${food._id}`)
@@ -391,7 +389,7 @@ describe("auth tests", () => {
391
389
  const getRes = await agent.get("/food").expect(200);
392
390
 
393
391
  expect(getRes.body.data).toHaveLength(4);
394
- const food = getRes.body.data.find((f: any) => f.name === "Apple");
392
+ const food = getRes.body.data.find((f: Food) => f.name === "Apple");
395
393
  expect(food).toBeDefined();
396
394
 
397
395
  const updateRes = await agent
@@ -431,7 +429,7 @@ describe("auth tests", () => {
431
429
  message: "Password or username is incorrect",
432
430
  });
433
431
  let user = await UserModel.findById(admin._id);
434
- expect((user as any)?.attempts).toBe(1);
432
+ expect((user as unknown as {attempts: number} | null)?.attempts).toBe(1);
435
433
  res = await agent
436
434
  .post("/auth/login")
437
435
  .send({email: "admin@example.com", password: "wrong"})
@@ -441,7 +439,7 @@ describe("auth tests", () => {
441
439
  message: "Password or username is incorrect",
442
440
  });
443
441
  user = await UserModel.findById(admin._id);
444
- expect((user as any)?.attempts).toBe(2);
442
+ expect((user as unknown as {attempts: number} | null)?.attempts).toBe(2);
445
443
  res = await agent
446
444
  .post("/auth/login")
447
445
  .send({email: "admin@example.com", password: "wrong"})
@@ -451,7 +449,7 @@ describe("auth tests", () => {
451
449
  message: "Account locked due to too many failed login attempts",
452
450
  });
453
451
  user = await UserModel.findById(admin._id);
454
- expect((user as any)?.attempts).toBe(3);
452
+ expect((user as unknown as {attempts: number} | null)?.attempts).toBe(3);
455
453
 
456
454
  // Logging in with correct password fails because account is locked
457
455
  res = await agent
@@ -464,7 +462,7 @@ describe("auth tests", () => {
464
462
  });
465
463
  user = await UserModel.findById(admin._id);
466
464
  // Not incremented
467
- expect((user as any)?.attempts).toBe(3);
465
+ expect((user as unknown as {attempts: number} | null)?.attempts).toBe(3);
468
466
  });
469
467
 
470
468
  it("refresh token allows refresh of auth token", async () => {
@@ -538,8 +536,8 @@ describe("auth tests", () => {
538
536
 
539
537
  describe("custom auth options", () => {
540
538
  let app: express.Application;
541
- let admin: any;
542
- let notAdmin: any;
539
+ let admin: Awaited<ReturnType<typeof setupDb>>[number];
540
+ let notAdmin: Awaited<ReturnType<typeof setupDb>>[number];
543
541
 
544
542
  beforeEach(async () => {
545
543
  // Reset to real time - don't freeze time here as passport-local-mongoose
@@ -569,7 +567,7 @@ describe("custom auth options", () => {
569
567
  }),
570
568
  ]);
571
569
  app = getBaseServer();
572
- addAuthRoutes(app, UserModel as any, {
570
+ addAuthRoutes(app, UserModel as unknown as AuthUserModel, {
573
571
  // custom refresh token logic based on admin or non admin
574
572
  generateTokenExpiration: (user?: {admin: boolean}) => {
575
573
  if (user?.admin) {
@@ -578,8 +576,8 @@ describe("custom auth options", () => {
578
576
  return "365d";
579
577
  },
580
578
  });
581
- setupAuth(app, UserModel as any);
582
- addMeRoutes(app, UserModel as any);
579
+ setupAuth(app, UserModel as unknown as AuthUserModel);
580
+ addMeRoutes(app, UserModel as unknown as AuthUserModel);
583
581
  app.use(
584
582
  "/food",
585
583
  modelRouter(FoodModel, {
@@ -734,29 +732,29 @@ describe("generateTokens edge cases", () => {
734
732
  });
735
733
 
736
734
  it("includes custom payload from generateJWTPayload option", async () => {
737
- const jwtLib = await import("jsonwebtoken");
738
-
739
735
  const user = {_id: "user-123"};
740
736
  const result = await generateTokens(user, {
741
737
  generateJWTPayload: (u) => ({customField: "customValue", userId: u._id}),
742
738
  });
743
739
 
744
740
  expect(result.token).toBeDefined();
745
- const decoded = jwtLib.decode(result.token as string) as any;
741
+ const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
742
+ result.token as string
743
+ );
746
744
  expect(decoded.customField).toBe("customValue");
747
745
  expect(decoded.id).toBe("user-123");
748
746
  });
749
747
 
750
748
  it("uses custom token expiration from generateTokenExpiration option", async () => {
751
- const jwtLib = await import("jsonwebtoken");
752
-
753
749
  const user = {_id: "user-123"};
754
750
  const result = await generateTokens(user, {
755
751
  generateTokenExpiration: () => "1h",
756
752
  });
757
753
 
758
754
  expect(result.token).toBeDefined();
759
- const decoded = jwtLib.decode(result.token as string) as any;
755
+ const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
756
+ result.token as string
757
+ );
760
758
  // Check that exp is roughly 1 hour from now (within 5 seconds tolerance)
761
759
  const expectedExp = Math.floor(Date.now() / 1000) + 3600;
762
760
  expect(decoded.exp).toBeGreaterThan(expectedExp - 5);
@@ -764,15 +762,15 @@ describe("generateTokens edge cases", () => {
764
762
  });
765
763
 
766
764
  it("uses custom refresh token expiration from generateRefreshTokenExpiration option", async () => {
767
- const jwtLib = await import("jsonwebtoken");
768
-
769
765
  const user = {_id: "user-123"};
770
766
  const result = await generateTokens(user, {
771
767
  generateRefreshTokenExpiration: () => "7d",
772
768
  });
773
769
 
774
770
  expect(result.refreshToken).toBeDefined();
775
- const decoded = jwtLib.decode(result.refreshToken as string) as any;
771
+ const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
772
+ result.refreshToken as string
773
+ );
776
774
  // Check that exp is roughly 7 days from now
777
775
  const expectedExp = Math.floor(Date.now() / 1000) + 7 * 24 * 3600;
778
776
  expect(decoded.exp).toBeGreaterThan(expectedExp - 10);
@@ -792,20 +790,22 @@ describe("generateTokens edge cases", () => {
792
790
  });
793
791
 
794
792
  it("uses TOKEN_EXPIRES_IN from env when valid", async () => {
795
- const jwtLib = await import("jsonwebtoken");
796
793
  process.env.TOKEN_EXPIRES_IN = "2h";
797
794
  const result = await generateTokens({_id: "user-123"});
798
- const decoded = jwtLib.decode(result.token as string) as any;
795
+ const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
796
+ result.token as string
797
+ );
799
798
  const expectedExp = Math.floor(Date.now() / 1000) + 2 * 3600;
800
799
  expect(decoded.exp).toBeGreaterThan(expectedExp - 10);
801
800
  expect(decoded.exp).toBeLessThan(expectedExp + 10);
802
801
  });
803
802
 
804
803
  it("uses REFRESH_TOKEN_EXPIRES_IN from env when valid", async () => {
805
- const jwtLib = await import("jsonwebtoken");
806
804
  process.env.REFRESH_TOKEN_EXPIRES_IN = "1h";
807
805
  const result = await generateTokens({_id: "user-123"});
808
- const decoded = jwtLib.decode(result.refreshToken as string) as any;
806
+ const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
807
+ result.refreshToken as string
808
+ );
809
809
  const expectedExp = Math.floor(Date.now() / 1000) + 3600;
810
810
  expect(decoded.exp).toBeGreaterThan(expectedExp - 10);
811
811
  expect(decoded.exp).toBeLessThan(expectedExp + 10);
@@ -904,7 +904,7 @@ describe("addAuthRoutes /refresh_token error paths", () => {
904
904
  const [adminUser] = await setupDb();
905
905
  const jwtLib = (await import("jsonwebtoken")).default;
906
906
  const validToken = jwtLib.sign(
907
- {id: (adminUser as any)._id.toString()},
907
+ {id: adminUser._id.toString()},
908
908
  process.env.REFRESH_TOKEN_SECRET as string
909
909
  );
910
910
  const res = await agent
@@ -926,7 +926,7 @@ describe("addMeRoutes edge cases", () => {
926
926
  app = new TerrenoApp({
927
927
  configureApp: () => {},
928
928
  skipListen: true,
929
- userModel: UserModel as any,
929
+ userModel: UserModel as unknown as AuthUserModel,
930
930
  }).build();
931
931
  agent = supertest.agent(app);
932
932
  });
@@ -946,13 +946,11 @@ describe("addMeRoutes edge cases", () => {
946
946
  it("GET /auth/me returns 404 when user is deleted after auth", async () => {
947
947
  const [_admin, notAdmin] = await setupDb();
948
948
  const jwtLib = (await import("jsonwebtoken")).default;
949
- const token = jwtLib.sign(
950
- {id: (notAdmin as any)._id.toString()},
951
- process.env.TOKEN_SECRET as string,
952
- {issuer: process.env.TOKEN_ISSUER}
953
- );
949
+ const token = jwtLib.sign({id: notAdmin._id.toString()}, process.env.TOKEN_SECRET as string, {
950
+ issuer: process.env.TOKEN_ISSUER,
951
+ });
954
952
  // Delete the user so findById returns null
955
- await UserModel.deleteOne({_id: (notAdmin as any)._id});
953
+ await UserModel.deleteOne({_id: notAdmin._id});
956
954
  const res = await agent.get("/auth/me").set("authorization", `Bearer ${token}`);
957
955
  // Either 404 (user not found in /me handler) or 401 (auth middleware rejects)
958
956
  expect([401, 404]).toContain(res.status);
@@ -998,7 +996,7 @@ describe("privileged user fields", () => {
998
996
  app = new TerrenoApp({
999
997
  configureApp: () => {},
1000
998
  skipListen: true,
1001
- userModel: UserModel as any,
999
+ userModel: UserModel as unknown as AuthUserModel,
1002
1000
  }).build();
1003
1001
  agent = supertest.agent(app);
1004
1002
  });
@@ -1007,14 +1005,16 @@ describe("privileged user fields", () => {
1007
1005
  setSystemTime();
1008
1006
  });
1009
1007
 
1010
- it("drops admin, roles, and organizationIds, keeping other fields", () => {
1008
+ it("drops admin, roles, organizationIds, emailVerified, and tokenEpoch, keeping other fields", () => {
1011
1009
  const sanitized = stripPrivilegedUserFields(
1012
1010
  {
1013
1011
  admin: true,
1014
1012
  age: 42,
1013
+ emailVerified: true,
1015
1014
  name: "Someone",
1016
1015
  organizationIds: ["other-tenant"],
1017
1016
  roles: ["superadmin"],
1017
+ tokenEpoch: 99,
1018
1018
  },
1019
1019
  "test"
1020
1020
  );
@@ -1026,8 +1026,14 @@ describe("privileged user fields", () => {
1026
1026
  expect(stripPrivilegedUserFields({name: "Someone"}, "test")).toEqual({name: "Someone"});
1027
1027
  });
1028
1028
 
1029
- it("lists admin, roles, and organizationIds as privileged", () => {
1030
- expect([...PRIVILEGED_USER_FIELDS]).toEqual(["admin", "roles", "organizationIds"]);
1029
+ it("lists admin, roles, organizationIds, emailVerified, and tokenEpoch as privileged", () => {
1030
+ expect([...PRIVILEGED_USER_FIELDS]).toEqual([
1031
+ "admin",
1032
+ "roles",
1033
+ "organizationIds",
1034
+ "emailVerified",
1035
+ "tokenEpoch",
1036
+ ]);
1031
1037
  });
1032
1038
 
1033
1039
  it("omits privileged User fields from ordinary RBAC modelRouter writes", () => {
@@ -1071,14 +1077,18 @@ describe("privileged user fields", () => {
1071
1077
  .send({
1072
1078
  admin: true,
1073
1079
  email: "escalate@example.com",
1080
+ emailVerified: true,
1074
1081
  organizationIds: ["other-tenant"],
1075
1082
  password: "Password123!",
1083
+ tokenEpoch: 99,
1076
1084
  })
1077
1085
  .expect(200);
1078
1086
 
1079
1087
  const created = await UserModel.findOne({email: "escalate@example.com"});
1080
1088
  expect(created).toBeTruthy();
1081
1089
  expect((created as unknown as {admin?: boolean})?.admin).toBe(false);
1090
+ expect((created as unknown as {emailVerified?: boolean})?.emailVerified).toBe(false);
1091
+ expect((created as unknown as {tokenEpoch?: number})?.tokenEpoch ?? 0).toBe(0);
1082
1092
  expect(
1083
1093
  (created as unknown as {organizationIds?: string[]})?.organizationIds ?? []
1084
1094
  ).not.toContain("other-tenant");
@@ -1107,16 +1117,62 @@ describe("privileged user fields", () => {
1107
1117
  await agent
1108
1118
  .patch("/auth/me")
1109
1119
  .set("authorization", `Bearer ${token}`)
1110
- .send({admin: true, name: "Renamed", organizationIds: ["other-tenant"]})
1120
+ .send({
1121
+ admin: true,
1122
+ emailVerified: true,
1123
+ name: "Renamed",
1124
+ organizationIds: ["other-tenant"],
1125
+ tokenEpoch: 99,
1126
+ })
1111
1127
  .expect(200);
1112
1128
 
1113
1129
  const reloaded = await UserModel.findById(notAdminId);
1114
1130
  expect((reloaded as unknown as {admin?: boolean})?.admin).toBe(false);
1131
+ expect((reloaded as unknown as {emailVerified?: boolean})?.emailVerified).toBe(false);
1132
+ expect((reloaded as unknown as {tokenEpoch?: number})?.tokenEpoch ?? 0).toBe(0);
1115
1133
  expect((reloaded as unknown as {name?: string})?.name).toBe("Renamed");
1116
1134
  expect(
1117
1135
  (reloaded as unknown as {organizationIds?: string[]})?.organizationIds ?? []
1118
1136
  ).not.toContain("other-tenant");
1119
1137
  });
1138
+
1139
+ it("clears email verification when PATCH /auth/me changes the mailbox", async () => {
1140
+ const [_admin, notAdmin] = await setupDb();
1141
+ const jwtLib = (await import("jsonwebtoken")).default;
1142
+ const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
1143
+ const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
1144
+ issuer: process.env.TOKEN_ISSUER,
1145
+ });
1146
+ await UserModel.findByIdAndUpdate(notAdminId, {$set: {emailVerified: true}});
1147
+
1148
+ await agent
1149
+ .patch("/auth/me")
1150
+ .set("authorization", `Bearer ${token}`)
1151
+ .send({email: "unproven@example.com"})
1152
+ .expect(200);
1153
+
1154
+ const reloaded = await UserModel.findById(notAdminId);
1155
+ expect((reloaded as unknown as {emailVerified?: boolean})?.emailVerified).toBe(false);
1156
+ });
1157
+
1158
+ it("keeps email verification for a casing-only email update", async () => {
1159
+ const [_admin, notAdmin] = await setupDb();
1160
+ const jwtLib = (await import("jsonwebtoken")).default;
1161
+ const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
1162
+ const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
1163
+ issuer: process.env.TOKEN_ISSUER,
1164
+ });
1165
+ await UserModel.findByIdAndUpdate(notAdminId, {$set: {emailVerified: true}});
1166
+
1167
+ await agent
1168
+ .patch("/auth/me")
1169
+ .set("authorization", `Bearer ${token}`)
1170
+ .send({email: "NOTADMIN@EXAMPLE.COM"})
1171
+ .expect(200);
1172
+
1173
+ const reloaded = await UserModel.findById(notAdminId);
1174
+ expect((reloaded as unknown as {emailVerified?: boolean})?.emailVerified).toBe(true);
1175
+ });
1120
1176
  });
1121
1177
 
1122
1178
  describe("Secret prefix authorization bypass", () => {
@@ -1143,7 +1199,7 @@ describe("Secret prefix authorization bypass", () => {
1143
1199
  );
1144
1200
  },
1145
1201
  skipListen: true,
1146
- userModel: UserModel as any,
1202
+ userModel: UserModel as unknown as AuthUserModel,
1147
1203
  }).build();
1148
1204
  agent = supertest.agent(app);
1149
1205
  });
@@ -1208,7 +1264,7 @@ describe("refresh_token without REFRESH_TOKEN_SECRET", () => {
1208
1264
  app = new TerrenoApp({
1209
1265
  configureApp: () => {},
1210
1266
  skipListen: true,
1211
- userModel: UserModel as any,
1267
+ userModel: UserModel as unknown as AuthUserModel,
1212
1268
  }).build();
1213
1269
  agent = supertest.agent(app);
1214
1270
  });
@@ -1274,7 +1330,7 @@ describe("JWT cookie extraction and /me routes edge cases", () => {
1274
1330
  app = new TerrenoApp({
1275
1331
  configureApp: () => {},
1276
1332
  skipListen: true,
1277
- userModel: UserModel as any,
1333
+ userModel: UserModel as unknown as AuthUserModel,
1278
1334
  }).build();
1279
1335
  agent = supertest.agent(app);
1280
1336
  });
@@ -1322,7 +1378,7 @@ describe("login error and disabled user paths", () => {
1322
1378
  app = new TerrenoApp({
1323
1379
  configureApp: () => {},
1324
1380
  skipListen: true,
1325
- userModel: UserModel as any,
1381
+ userModel: UserModel as unknown as AuthUserModel,
1326
1382
  }).build();
1327
1383
  agent = supertest.agent(app);
1328
1384
  });
@@ -1370,7 +1426,7 @@ describe("PATCH /me route edge cases", () => {
1370
1426
  app = new TerrenoApp({
1371
1427
  configureApp: () => {},
1372
1428
  skipListen: true,
1373
- userModel: UserModel as any,
1429
+ userModel: UserModel as unknown as AuthUserModel,
1374
1430
  }).build();
1375
1431
  agent = supertest.agent(app);
1376
1432
  });
@@ -1430,7 +1486,7 @@ describe("JWT strategy createAnonymousUser path", () => {
1430
1486
  );
1431
1487
  },
1432
1488
  skipListen: true,
1433
- userModel: UserModel as any,
1489
+ userModel: UserModel as unknown as AuthUserModel,
1434
1490
  }).build();
1435
1491
  agent = supertest.agent(app);
1436
1492
  });
@@ -1501,7 +1557,7 @@ describe("decodeJWTMiddleware error paths", () => {
1501
1557
  );
1502
1558
  },
1503
1559
  skipListen: true,
1504
- userModel: UserModel as any,
1560
+ userModel: UserModel as unknown as AuthUserModel,
1505
1561
  }).build();
1506
1562
  agent = supertest.agent(app);
1507
1563
  });
@@ -1588,7 +1644,7 @@ describe("signup disabled", () => {
1588
1644
  app = new TerrenoApp({
1589
1645
  configureApp: () => {},
1590
1646
  skipListen: true,
1591
- userModel: UserModel as any,
1647
+ userModel: UserModel as unknown as AuthUserModel,
1592
1648
  }).build();
1593
1649
  agent = supertest.agent(app);
1594
1650
  });
@@ -1758,7 +1814,7 @@ describe("auth error paths when the user lookup fails", () => {
1758
1814
  app = new TerrenoApp({
1759
1815
  configureApp: () => {},
1760
1816
  skipListen: true,
1761
- userModel: UserModel as any,
1817
+ userModel: UserModel as unknown as AuthUserModel,
1762
1818
  }).build();
1763
1819
  agent = supertest.agent(app);
1764
1820
  });
@@ -1799,7 +1855,7 @@ describe("auth error paths when the user lookup fails", () => {
1799
1855
  const errApp = new TerrenoApp({
1800
1856
  configureApp: () => {},
1801
1857
  skipListen: true,
1802
- userModel: UserModel as any,
1858
+ userModel: UserModel as unknown as AuthUserModel,
1803
1859
  }).build();
1804
1860
  const errAgent = supertest.agent(errApp);
1805
1861
  const res = await errAgent
package/src/auth.ts CHANGED
@@ -2,7 +2,7 @@ import {randomUUID} from "node:crypto";
2
2
  import express from "express";
3
3
  import jwt, {type JwtPayload} from "jsonwebtoken";
4
4
  import {DateTime} from "luxon";
5
- import type {Model, ObjectId} from "mongoose";
5
+ import type {Model, ObjectId, Query} from "mongoose";
6
6
  import ms, {type StringValue} from "ms";
7
7
  import passport from "passport";
8
8
  import {Strategy as AnonymousStrategy} from "passport-anonymous";
@@ -12,10 +12,12 @@ import {
12
12
  type StrategyOptions,
13
13
  } from "passport-jwt";
14
14
  import {Strategy as LocalStrategy} from "passport-local";
15
-
15
+ import {addAuthRecoveryRoutes, sendVerificationEmail} from "./authRecovery";
16
+ import {AuthToken} from "./authTokens";
16
17
  import {APIError, apiErrorMiddleware, errorMessage} from "./errors";
17
18
  import type {AuthOptions} from "./expressServer";
18
19
  import {logger} from "./logger";
20
+ import {isJwtCredentialExchangePath} from "./rateLimit/policies";
19
21
  import {
20
22
  getSessionIdFromJwtPayload,
21
23
  type JwtSessionPayload,
@@ -34,6 +36,12 @@ export interface User {
34
36
  * This can be helpful for pre-signup users.
35
37
  */
36
38
  isAnonymous?: boolean;
39
+ /** Login identifier; present on passport-local and Better Auth app users. */
40
+ email?: string;
41
+ /** Incremented on password reset so outstanding refresh tokens fail. */
42
+ tokenEpoch?: number;
43
+ /** Set by emailVerificationPlugin; login may require this when requireEmailVerification is on. */
44
+ emailVerified?: boolean;
37
45
  }
38
46
 
39
47
  export interface UserModel extends Model<User> {
@@ -41,18 +49,14 @@ export interface UserModel extends Model<User> {
41
49
  // Allows additional setup during signup. This will be passed the rest of req.body from the signup
42
50
  postCreate?: (body: Record<string, unknown>) => Promise<void>;
43
51
 
44
- // noExplicitAny: passport-local-mongoose return types are untyped
45
- // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
46
- createStrategy(): any;
47
- // noExplicitAny: passport-local-mongoose return types are untyped
48
- // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
49
- serializeUser(): any;
50
- // noExplicitAny: passport-local-mongoose return types are untyped
51
- // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
52
- deserializeUser(): any;
53
- // noExplicitAny: passport-local-mongoose return types are untyped
54
- // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
55
- findByUsername(username: string, findOpts: any): any;
52
+ // Provided by passport-local-mongoose:
53
+ createStrategy(): passport.Strategy;
54
+ serializeUser(): (user: User, cb: (err: unknown, id?: unknown) => void) => void;
55
+ deserializeUser(): (username: string, cb: (err: unknown, user?: User | null) => void) => void;
56
+ findByUsername(
57
+ username: string,
58
+ findOpts: boolean | {selectHashSaltFields?: boolean}
59
+ ): Query<User | null, User>;
56
60
  }
57
61
 
58
62
  export interface GenerateTokensOptions {
@@ -101,11 +105,18 @@ export const authenticateMiddleware = (anonymous = false) => {
101
105
  };
102
106
 
103
107
  /**
104
- * User fields that confer authority. Self-service requests (anonymous signup, `PATCH /me`)
105
- * must never set them, or any caller could grant themselves admin or an RBAC role. Elevate
106
- * users through the admin API or `access.roles.assign` instead.
108
+ * User fields that confer authority or skip security gates. Self-service requests
109
+ * (anonymous signup, `PATCH /me`) must never set them, or any caller could grant
110
+ * themselves admin, an RBAC role, a verified email, or a reset epoch. Elevate users
111
+ * through the admin API or `access.roles.assign` instead.
107
112
  */
108
- export const PRIVILEGED_USER_FIELDS = ["admin", "roles", "organizationIds"] as const;
113
+ export const PRIVILEGED_USER_FIELDS = [
114
+ "admin",
115
+ "roles",
116
+ "organizationIds",
117
+ "emailVerified",
118
+ "tokenEpoch",
119
+ ] as const;
109
120
 
110
121
  /**
111
122
  * Removes {@link PRIVILEGED_USER_FIELDS} from a self-service body. Fields are dropped rather
@@ -130,6 +141,13 @@ export const stripPrivilegedUserFields = (
130
141
  return sanitized;
131
142
  };
132
143
 
144
+ const isEmailUpdateChangingMailbox = (currentEmail: unknown, nextEmail: unknown): boolean => {
145
+ if (typeof currentEmail !== "string" || typeof nextEmail !== "string") {
146
+ return false;
147
+ }
148
+ return currentEmail.trim().toLowerCase() !== nextEmail.trim().toLowerCase();
149
+ };
150
+
133
151
  const omitPrivilegedFieldsFromObject = (item: unknown, allowAdminWrite: boolean): unknown => {
134
152
  if (!item || typeof item !== "object" || Array.isArray(item)) {
135
153
  return item;
@@ -181,9 +199,18 @@ export const signupUser = async (
181
199
  const bodyRest = stripPrivilegedUserFields(rawBody, "signup");
182
200
 
183
201
  try {
184
- // noExplicitAny: passport-local-mongoose's register() is untyped
185
- // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose's register() is untyped
186
- const user = await (userModel as any).register({email, ...bodyRest}, password);
202
+ const registrableModel = userModel as UserModel & {
203
+ register(
204
+ user: Record<string, unknown>,
205
+ password: string
206
+ ): Promise<
207
+ User & {
208
+ postCreate?: (body: Record<string, unknown>) => Promise<void>;
209
+ save: () => Promise<unknown>;
210
+ }
211
+ >;
212
+ };
213
+ const user = await registrableModel.register({email, ...bodyRest}, password);
187
214
 
188
215
  if (user.postCreate) {
189
216
  try {
@@ -341,15 +368,20 @@ export const generateTokens = async (
341
368
  return {refreshToken: null, token: null};
342
369
  }
343
370
  const sessionId = options.sessionId ?? randomUUID();
344
- let payload: Record<string, unknown> = {id: String(tokenUser._id), sid: sessionId};
371
+ const authUser = user as User;
372
+ let payload: Record<string, unknown> = {
373
+ id: String(tokenUser._id),
374
+ sid: sessionId,
375
+ te: authUser.tokenEpoch ?? 0,
376
+ };
345
377
  if (authOptions?.generateJWTPayload) {
346
- payload = {...authOptions.generateJWTPayload(user), ...payload};
378
+ payload = {...authOptions.generateJWTPayload(authUser), ...payload};
347
379
  }
348
380
  const tokenOptions: jwt.SignOptions = {
349
381
  expiresIn: "15m",
350
382
  };
351
383
  if (authOptions?.generateTokenExpiration) {
352
- tokenOptions.expiresIn = authOptions.generateTokenExpiration(user);
384
+ tokenOptions.expiresIn = authOptions.generateTokenExpiration(authUser);
353
385
  } else if (process.env.TOKEN_EXPIRES_IN) {
354
386
  const expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
355
387
  if (expiresIn) {
@@ -368,7 +400,7 @@ export const generateTokens = async (
368
400
  expiresIn: "30d",
369
401
  };
370
402
  if (authOptions?.generateRefreshTokenExpiration) {
371
- refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(user);
403
+ refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(authUser);
372
404
  } else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
373
405
  const expiresIn = validateDuration(
374
406
  "REFRESH_TOKEN_EXPIRES_IN",
@@ -469,6 +501,12 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
469
501
  return next();
470
502
  }
471
503
 
504
+ // Login, signup, and refresh exchange credentials. A stale access JWT in
505
+ // Authorization / the jwt cookie must not 401 before those handlers run.
506
+ if (isJwtCredentialExchangePath(req)) {
507
+ return next();
508
+ }
509
+
472
510
  // Allow requests with a "Secret" prefix to pass through since this is a string value,
473
511
  // not a jwt that needs to be decoded
474
512
  if (req?.headers?.authorization?.split(" ")[0] === "Secret") {
@@ -535,9 +573,8 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
535
573
  return next();
536
574
  };
537
575
  app.use(decodeJWTMiddleware);
538
- // noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
539
- // biome-ignore lint/suspicious/noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
540
- app.use(express.urlencoded({extended: false}) as any);
576
+ // express 5's urlencoded() handler type doesn't match RequestHandler directly
577
+ app.use(express.urlencoded({extended: false}) as unknown as express.RequestHandler);
541
578
  };
542
579
 
543
580
  export const addAuthRoutes = (
@@ -563,6 +600,15 @@ export const addAuthRoutes = (
563
600
  logger.warn(`Invalid login: ${info}`);
564
601
  return res.status(401).json({message: info?.message});
565
602
  }
603
+ if (authOptions?.requireEmailVerification && user.emailVerified !== true) {
604
+ return next(
605
+ new APIError({
606
+ code: "email-not-verified",
607
+ status: 403,
608
+ title: "Email is not verified",
609
+ })
610
+ );
611
+ }
566
612
  if (process.env.NODE_ENV !== "test") {
567
613
  logger.info(`User logged in: ${user._id}, type: ${user.type || "N/A"}`);
568
614
  }
@@ -602,6 +648,12 @@ export const addAuthRoutes = (
602
648
  }
603
649
  if (decoded?.id) {
604
650
  const user = await userModel.findById(decoded.id);
651
+ const tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
652
+ const userEpoch = (user as User | null)?.tokenEpoch ?? 0;
653
+ if (!user || tokenEpoch !== userEpoch) {
654
+ logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
655
+ return res.status(401).json({message: "Invalid refresh token"});
656
+ }
605
657
  const sessionId = getSessionIdFromJwtPayload(decoded as JwtSessionPayload);
606
658
  const tokens = await generateTokens(user, authOptions, {sessionId});
607
659
  if (tokens.sessionId) {
@@ -643,6 +695,13 @@ export const addAuthRoutes = (
643
695
  )(req, res, next);
644
696
  },
645
697
  async (req: express.Request, res: express.Response) => {
698
+ if (req.user) {
699
+ try {
700
+ await sendVerificationEmail(req.user, authOptions);
701
+ } catch (error: unknown) {
702
+ logger.error("[auth] Failed to send verification mail after signup", {error});
703
+ }
704
+ }
646
705
  const tokens = await generateTokens(req.user, authOptions);
647
706
  if (tokens.sessionId) {
648
707
  setRequestContext({
@@ -659,6 +718,7 @@ export const addAuthRoutes = (
659
718
  }
660
719
  app.set("etag", false);
661
720
  app.use("/auth", router);
721
+ addAuthRecoveryRoutes(app, userModel, authOptions);
662
722
  };
663
723
 
664
724
  export const addMeRoutes = (
@@ -705,7 +765,16 @@ export const addMeRoutes = (
705
765
  // return res.status(403).send({message: (e as Error).message});
706
766
  // }
707
767
  try {
708
- Object.assign(doc, stripPrivilegedUserFields(req.body ?? {}, "PATCH /auth/me"));
768
+ const update = stripPrivilegedUserFields(req.body ?? {}, "PATCH /auth/me");
769
+ const isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
770
+ Object.assign(doc, update);
771
+ if (isMailboxChange) {
772
+ await AuthToken.invalidateUnusedFor({_id: String(doc._id)}, "passwordReset");
773
+ if (userModel.schema.path("emailVerified") !== undefined) {
774
+ doc.emailVerified = false;
775
+ await AuthToken.invalidateUnusedFor({_id: String(doc._id)}, "emailVerification");
776
+ }
777
+ }
709
778
  await doc.save();
710
779
 
711
780
  const dataObject = doc.toObject() as unknown as Record<string, unknown>;