create-tigra 4.1.0 → 5.0.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 (142) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -1
  3. package/bin/create-tigra.js +68 -73
  4. package/lib/installer-transaction.js +275 -0
  5. package/lib/patchers/diagnostics.patcher.js +33 -59
  6. package/lib/patchers/email-verification.patcher.js +86 -92
  7. package/lib/patchers/metrics.patcher.js +18 -18
  8. package/lib/project-files.js +99 -0
  9. package/modules/diagnostics/diagnostics.md +10 -0
  10. package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
  11. package/modules/diagnostics/prisma/migration.sql +1 -24
  12. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
  13. package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
  14. package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
  15. package/modules/email-verification/client/hooks/useVerification.ts +4 -7
  16. package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
  17. package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
  18. package/modules/email-verification/server/verification.service.ts +102 -157
  19. package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
  20. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
  21. package/modules/metrics/performance.md +2 -2
  22. package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
  23. package/modules/metrics/server/metrics.collector.ts +6 -3
  24. package/modules/metrics/server/metrics.routes.ts +1 -2
  25. package/modules/metrics/server/metrics.service.ts +6 -2
  26. package/package.json +1 -1
  27. package/template/AGENTS.md +4 -3
  28. package/template/client/.dockerignore +2 -5
  29. package/template/client/gitignore +43 -0
  30. package/template/client/package-lock.json +51 -51
  31. package/template/client/package.json +2 -2
  32. package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
  33. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  34. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  35. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  36. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  37. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  38. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  39. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  40. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  41. package/template/client/src/lib/api/axios.config.ts +24 -6
  42. package/template/client/src/lib/api/session-events.ts +54 -0
  43. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  44. package/template/client/src/store/__tests__/store.test.ts +1 -0
  45. package/template/gitignore +3 -2
  46. package/template/server/.dockerignore +2 -5
  47. package/template/server/.env.example +1 -0
  48. package/template/server/.env.example.production +1 -0
  49. package/template/server/README.md +7 -2
  50. package/template/server/docs/deployment.md +66 -0
  51. package/template/server/docs/logging.md +9 -8
  52. package/template/server/docs/rate-limits.md +6 -4
  53. package/template/server/gitignore +33 -0
  54. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  55. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  56. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  57. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  58. package/template/server/prisma/schema.prisma +25 -1
  59. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  60. package/template/server/src/app.ts +14 -5
  61. package/template/server/src/config/env.ts +8 -0
  62. package/template/server/src/config/rate-limit.config.ts +1 -1
  63. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  64. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  65. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  66. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  67. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  68. package/template/server/src/jobs/index.ts +8 -2
  69. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  70. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  71. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  72. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  73. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  74. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  75. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  76. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  77. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  78. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  79. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  80. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  81. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  82. package/template/server/src/libs/account-mutation.ts +77 -0
  83. package/template/server/src/libs/auth.ts +37 -3
  84. package/template/server/src/libs/cookies.ts +25 -13
  85. package/template/server/src/libs/email-quota.ts +11 -7
  86. package/template/server/src/libs/email.ts +11 -8
  87. package/template/server/src/libs/error-handler.ts +16 -12
  88. package/template/server/src/libs/http.ts +37 -13
  89. package/template/server/src/libs/ip-block.ts +56 -34
  90. package/template/server/src/libs/logger.ts +23 -8
  91. package/template/server/src/libs/monitoring.ts +57 -31
  92. package/template/server/src/libs/observability/sentry.ts +65 -49
  93. package/template/server/src/libs/prisma.ts +1 -1
  94. package/template/server/src/libs/private-cache.ts +6 -0
  95. package/template/server/src/libs/rate-limiting.ts +4 -0
  96. package/template/server/src/libs/requestLogger.ts +3 -3
  97. package/template/server/src/libs/safe-http.ts +58 -18
  98. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  99. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  100. package/template/server/src/libs/storage/file-validator.ts +2 -1
  101. package/template/server/src/libs/url-safety.ts +10 -2
  102. package/template/server/src/libs/validation-errors.ts +11 -8
  103. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  104. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  105. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  106. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  107. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  108. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  109. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  110. package/template/server/src/modules/admin/admin.service.ts +61 -62
  111. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  112. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  113. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  114. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  115. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  116. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  117. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  118. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  119. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  120. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  121. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  122. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  123. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  124. package/template/server/src/modules/auth/auth.service.ts +33 -237
  125. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  126. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  127. package/template/server/src/modules/auth/session.repo.ts +5 -4
  128. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  129. package/template/server/src/modules/files/files.controller.ts +2 -2
  130. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  131. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  132. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  133. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  134. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  135. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  136. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  137. package/template/server/src/modules/users/users.controller.ts +28 -25
  138. package/template/server/src/modules/users/users.repo.ts +12 -51
  139. package/template/server/src/modules/users/users.service.ts +109 -234
  140. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  141. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  142. package/template/server/src/test/setup.ts +4 -0
@@ -35,7 +35,7 @@ const mockRedis = vi.hoisted(() => ({
35
35
  expire: vi.fn(),
36
36
  set: vi.fn(),
37
37
  get: vi.fn(),
38
- getdel: vi.fn(),
38
+ eval: vi.fn(),
39
39
  del: vi.fn(),
40
40
  }));
41
41
 
@@ -55,6 +55,7 @@ describe('Auth Service', () => {
55
55
  vi.mocked(hashPassword).mockResolvedValue('dummy-hash');
56
56
  mockRedis.incr.mockResolvedValue(1);
57
57
  mockRedis.expire.mockResolvedValue(1);
58
+ mockRedis.eval.mockResolvedValue(0);
58
59
  mockRedis.set.mockResolvedValue('OK');
59
60
  mockRedis.del.mockResolvedValue(1);
60
61
  // refresh() requires the token's session to exist and be unexpired
@@ -192,6 +193,14 @@ describe('Auth Service', () => {
192
193
  });
193
194
  });
194
195
 
196
+ it('accepts a recovery request without looking up the account in the HTTP path', async () => {
197
+ vi.mocked(authRepo.findUserByEmail).mockResolvedValue(null);
198
+
199
+ await authService.forgotPassword('recovery@example.test');
200
+
201
+ expect(authRepo.findUserByEmail).not.toHaveBeenCalled();
202
+ });
203
+
195
204
  describe('login', () => {
196
205
  const validLoginInput = {
197
206
  email: 'test@example.com',
@@ -209,7 +218,7 @@ describe('Auth Service', () => {
209
218
  vi.mocked(authLib.signAccessToken).mockReturnValue(accessToken);
210
219
  vi.mocked(authLib.generateRefreshToken).mockReturnValue(refreshToken);
211
220
  vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(expiresAt);
212
- vi.mocked(sessionRepository.createSession).mockResolvedValue(testSession);
221
+ vi.mocked(authRepo.createLoginSession).mockResolvedValue(testSession);
213
222
  vi.mocked(authRepo.createRefreshToken).mockResolvedValue(testRefreshToken);
214
223
 
215
224
  // Act
@@ -218,18 +227,14 @@ describe('Auth Service', () => {
218
227
  // Assert
219
228
  expect(authRepo.findUserByEmail).toHaveBeenCalledWith(validLoginInput.email);
220
229
  expect(verifyPassword).toHaveBeenCalledWith(validLoginInput.password, testUsers.validUser.password);
221
- expect(sessionRepository.createSession).toHaveBeenCalledWith({
230
+ expect(authRepo.createLoginSession).toHaveBeenCalledWith({
222
231
  userId: testUsers.validUser.id,
232
+ verifiedPasswordHash: testUsers.validUser.password,
233
+ refreshToken,
223
234
  deviceInfo: undefined,
224
235
  ipAddress: undefined,
225
236
  expiresAt,
226
237
  });
227
- expect(authRepo.createRefreshToken).toHaveBeenCalledWith({
228
- token: refreshToken,
229
- userId: testUsers.validUser.id,
230
- sessionId: testSession.id,
231
- expiresAt,
232
- });
233
238
  expect(result).toEqual({
234
239
  user: expect.objectContaining({
235
240
  id: testUsers.validUser.id,
@@ -385,7 +390,7 @@ describe('Auth Service', () => {
385
390
  vi.mocked(authLib.signAccessToken).mockReturnValue('access');
386
391
  vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
387
392
  vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(expiresAt);
388
- vi.mocked(sessionRepository.createSession).mockResolvedValue(testSession);
393
+ vi.mocked(authRepo.createLoginSession).mockResolvedValue(testSession);
389
394
  vi.mocked(authRepo.createRefreshToken).mockResolvedValue(testRefreshToken);
390
395
 
391
396
  // Act
@@ -474,7 +479,7 @@ describe('Auth Service', () => {
474
479
  vi.mocked(authLib.signAccessToken).mockReturnValue('access');
475
480
  vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
476
481
  vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(expiresAt);
477
- vi.mocked(sessionRepository.createSession).mockResolvedValue(testSession);
482
+ vi.mocked(authRepo.createLoginSession).mockResolvedValue(testSession);
478
483
  vi.mocked(authRepo.createRefreshToken).mockResolvedValue(testRefreshToken);
479
484
 
480
485
  // Act
@@ -490,279 +495,43 @@ describe('Auth Service', () => {
490
495
  });
491
496
 
492
497
  describe('refresh', () => {
493
- const validRefreshToken = 'valid-refresh-token';
494
-
495
- it('should reject and delete a token whose session no longer exists', async () => {
496
- // e.g. the session was force-expired by an admin or removed by the cleanup job
497
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
498
- ...testRefreshToken,
499
- sessionId: testSession.id,
500
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
501
- });
502
- vi.mocked(sessionRepository.getSessionById).mockResolvedValue(null);
503
-
504
- await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'SESSION_EXPIRED' });
505
- expect(authRepo.deleteRefreshToken).toHaveBeenCalledWith(validRefreshToken);
506
- expect(authRepo.rotateRefreshToken).not.toHaveBeenCalled();
507
- expect(authLib.signAccessToken).not.toHaveBeenCalled();
508
- });
509
-
510
- it('should reject a token whose session has expired', async () => {
511
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
512
- ...testRefreshToken,
513
- sessionId: testSession.id,
514
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
515
- });
516
- vi.mocked(sessionRepository.getSessionById).mockResolvedValue({
517
- ...testSession,
518
- expiresAt: new Date(Date.now() - 1000),
519
- });
520
-
521
- await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'SESSION_EXPIRED' });
522
- expect(authRepo.rotateRefreshToken).not.toHaveBeenCalled();
523
- });
524
-
525
- it('should reject a legacy token that has no session at all', async () => {
526
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
527
- ...testRefreshToken,
528
- sessionId: null,
529
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
530
- });
531
-
532
- await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'SESSION_EXPIRED' });
533
- });
534
-
535
- it('should successfully refresh tokens with valid refresh token', async () => {
536
- // Arrange
537
- const newAccessToken = 'new-access-token';
538
- const newRefreshToken = 'new-refresh-token';
539
- const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
540
- const storedToken = {
541
- ...testRefreshToken,
542
- sessionId: testSession.id,
543
- token: validRefreshToken,
544
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // expires in 1 day
545
- };
546
-
547
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
548
- vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
549
- vi.mocked(authLib.signAccessToken).mockReturnValue(newAccessToken);
550
- vi.mocked(authLib.generateRefreshToken).mockReturnValue(newRefreshToken);
551
- vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(expiresAt);
552
- vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(true);
553
-
554
- // Act
555
- const result = await authService.refresh(validRefreshToken);
556
-
557
- // Assert
558
- expect(authRepo.findRefreshToken).toHaveBeenCalledWith(validRefreshToken);
559
- expect(authRepo.findUserById).toHaveBeenCalledWith(storedToken.userId);
560
- expect(authLib.signAccessToken).toHaveBeenCalledWith({
561
- userId: testUsers.validUser.id,
562
- role: testUsers.validUser.role,
563
- sessionId: testSession.id,
564
- });
565
- expect(authRepo.rotateRefreshToken).toHaveBeenCalledWith(validRefreshToken, {
566
- token: newRefreshToken,
567
- userId: testUsers.validUser.id,
568
- sessionId: testSession.id,
569
- expiresAt,
570
- });
571
- expect(result).toEqual({
572
- accessToken: newAccessToken,
573
- refreshToken: newRefreshToken,
574
- });
575
- });
576
-
577
- it('should throw UnauthorizedError if refresh token not found', async () => {
578
- // Arrange
579
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(null);
580
-
581
- // Act & Assert
582
- await expect(authService.refresh(validRefreshToken)).rejects.toThrow(UnauthorizedError);
583
- await expect(authService.refresh(validRefreshToken)).rejects.toThrow('Invalid refresh token');
584
- });
585
-
586
- it('should throw UnauthorizedError if refresh token expired', async () => {
587
- // Arrange
588
- const expiredToken = {
589
- ...testRefreshToken,
590
- sessionId: testSession.id,
591
- expiresAt: new Date(Date.now() - 1000), // expired 1 second ago
592
- };
593
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(expiredToken);
594
- vi.mocked(authRepo.deleteRefreshToken).mockResolvedValue(undefined);
595
-
596
- // Act & Assert
597
- await expect(authService.refresh(validRefreshToken)).rejects.toThrow(UnauthorizedError);
598
- await expect(authService.refresh(validRefreshToken)).rejects.toThrow('Refresh token expired');
599
- expect(authRepo.deleteRefreshToken).toHaveBeenCalledWith(validRefreshToken);
600
- });
601
-
602
- it('should throw UnauthorizedError if user not found', async () => {
603
- // Arrange
604
- const storedToken = {
605
- ...testRefreshToken,
606
- sessionId: testSession.id,
607
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
608
- };
609
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
610
- vi.mocked(authRepo.findUserById).mockResolvedValue(null);
611
-
612
- // Act & Assert
613
- await expect(authService.refresh(validRefreshToken)).rejects.toThrow(UnauthorizedError);
614
- await expect(authService.refresh(validRefreshToken)).rejects.toThrow('User not found or disabled');
615
- });
616
-
617
- it('should refuse to refresh a banned account', async () => {
618
- // Arrange
619
- const storedToken = {
620
- ...testRefreshToken,
621
- sessionId: testSession.id,
622
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
623
- };
624
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
625
- vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.inactiveUser);
626
-
627
- // Act & Assert
628
- await expect(authService.refresh(validRefreshToken)).rejects.toThrow(ForbiddenError);
629
- await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({
630
- code: 'ACCOUNT_DEACTIVATED',
631
- });
498
+ const token = 'valid-refresh-token';
499
+
500
+ it.each([
501
+ ['invalid', 'INVALID_REFRESH_TOKEN'],
502
+ ['expired-token', 'REFRESH_TOKEN_EXPIRED'],
503
+ ['expired-session', 'SESSION_EXPIRED'],
504
+ ['rotated', 'REFRESH_TOKEN_ROTATED'],
505
+ ] as const)('rejects a %s transaction outcome without issuing credentials', async (kind, code) => {
506
+ vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue({ kind });
507
+ await expect(authService.refresh(token)).rejects.toMatchObject({ statusCode: 401, code });
632
508
  expect(authLib.signAccessToken).not.toHaveBeenCalled();
633
509
  });
634
510
 
635
- it('a refresh whose token was rotated a moment ago by a parallel one is a lost race (cookies kept)', async () => {
636
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(null);
637
- mockRedis.exists.mockResolvedValue(1); // the winner's "just rotated" note
638
- await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({
639
- statusCode: 401,
640
- code: 'REFRESH_TOKEN_ROTATED',
641
- });
642
- expect(mockRedis.exists).toHaveBeenCalledWith(expect.stringMatching(/^rt-rotated:[0-9a-f]{64}$/));
643
- });
644
-
645
- it('an unknown refresh token without that note is still INVALID_REFRESH_TOKEN', async () => {
646
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(null);
647
- mockRedis.exists.mockResolvedValue(0);
648
- await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'INVALID_REFRESH_TOKEN' });
649
- });
650
-
651
- it('notes the rotation (fingerprint key, 60 s) before rotating', async () => {
652
- const storedToken = { ...testRefreshToken, sessionId: testSession.id, expiresAt: new Date(Date.now() + 86_400_000) };
653
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
654
- vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
655
- vi.mocked(authLib.signAccessToken).mockReturnValue('access');
656
- vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
657
- vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(new Date());
658
- vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(true);
659
-
660
- await authService.refresh(validRefreshToken);
661
-
662
- const note = mockRedis.set.mock.calls.find(([key]) => String(key).startsWith('rt-rotated:'));
663
- expect(note).toEqual([expect.stringMatching(/^rt-rotated:[0-9a-f]{64}$/), '1', 'EX', 60]);
664
- expect(String(note?.[0])).not.toContain(validRefreshToken);
665
- expect(mockRedis.set.mock.invocationCallOrder[mockRedis.set.mock.calls.indexOf(note as never)]).toBeLessThan(
666
- vi.mocked(authRepo.rotateRefreshToken).mock.invocationCallOrder[0] as number,
667
- );
668
- });
511
+ it('signs the access token from the committed session and role', async () => {
512
+ const claims = { userId: 'user', sessionId: 'session', role: 'USER' as const };
513
+ vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue({ kind: 'issued', claims });
514
+ vi.mocked(authLib.generateRefreshToken).mockReturnValue('new-refresh');
515
+ vi.mocked(authLib.signAccessToken).mockReturnValue('new-access');
669
516
 
670
- it('a refresh that loses a race with a parallel one is refused alone: nothing is revoked', async () => {
671
- // Two tabs share the cookie and refresh at the same moment; the atomic
672
- // rotation lets one win. The loser must get its own code (so the
673
- // controller keeps the winner's cookies) and must NOT wipe the user's
674
- // sessions: that used to sign the user out on every device.
675
- const storedToken = {
676
- ...testRefreshToken,
677
- sessionId: testSession.id,
678
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
679
- };
680
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
681
- vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
682
- vi.mocked(authLib.signAccessToken).mockReturnValue('access');
683
- vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
684
- vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(new Date());
685
- vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(false); // the parallel request rotated it first
686
-
687
- await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({
688
- statusCode: 401,
689
- code: 'REFRESH_TOKEN_ROTATED',
517
+ await expect(authService.refresh(token)).resolves.toEqual({
518
+ accessToken: 'new-access', refreshToken: 'new-refresh',
690
519
  });
691
- expect(authRepo.deleteRefreshTokensByUserId).not.toHaveBeenCalled();
692
- expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
693
- });
694
-
695
- it('should NOT revoke the token family on a successful rotation', async () => {
696
- // Companion to the race test: nothing is revoked on a normal rotation either.
697
- const storedToken = {
698
- ...testRefreshToken,
699
- sessionId: testSession.id,
700
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
701
- };
702
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
703
- vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
704
- vi.mocked(authLib.signAccessToken).mockReturnValue('access');
705
- vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
706
- vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(new Date());
707
- vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(true);
708
-
709
- // Act
710
- await authService.refresh(validRefreshToken);
711
-
712
- // Assert
713
- expect(authRepo.deleteRefreshTokensByUserId).not.toHaveBeenCalled();
714
- expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
520
+ expect(authLib.signAccessToken).toHaveBeenCalledWith(claims);
521
+ expect(mockRedis.set).not.toHaveBeenCalled();
715
522
  });
716
523
  });
717
524
 
718
525
  describe('logout', () => {
719
- it('should delete refresh token and its linked session', async () => {
720
- // Arrange
721
- const refreshToken = 'valid-refresh-token';
722
- const storedToken = {
723
- ...testRefreshToken,
724
- token: refreshToken,
725
- sessionId: 'session-1',
726
- };
727
-
728
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
729
- vi.mocked(authRepo.deleteRefreshToken).mockResolvedValue(undefined);
730
- vi.mocked(sessionRepository.deleteSession).mockResolvedValue(undefined as never);
731
-
732
- // Act
733
- await authService.logout(refreshToken);
734
-
735
- // Assert
736
- expect(authRepo.findRefreshToken).toHaveBeenCalledWith(refreshToken);
737
- expect(authRepo.deleteRefreshToken).toHaveBeenCalledWith(refreshToken);
738
- expect(sessionRepository.deleteSession).toHaveBeenCalledWith('session-1');
526
+ it('passes a verified access session and lets the repository revoke it atomically', async () => {
527
+ const session = { userId: 'user', sessionId: 'session' };
528
+ await authService.logout('refresh', session);
529
+ expect(authRepo.revokeSession).toHaveBeenCalledWith('refresh', session);
739
530
  });
740
531
 
741
- it('should not delete a session when the token has no sessionId', async () => {
742
- // Arrange — testRefreshToken fixture has sessionId: null
743
- const refreshToken = 'valid-refresh-token';
744
- vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
745
- ...testRefreshToken,
746
- token: refreshToken,
747
- });
748
- vi.mocked(authRepo.deleteRefreshToken).mockResolvedValue(undefined);
749
-
750
- // Act
751
- await authService.logout(refreshToken);
752
-
753
- // Assert
754
- expect(authRepo.deleteRefreshToken).toHaveBeenCalledWith(refreshToken);
755
- expect(sessionRepository.deleteSession).not.toHaveBeenCalled();
756
- });
757
-
758
- it('should propagate unexpected repository errors', async () => {
759
- // "Token already deleted" is handled gracefully inside the repo (P2025);
760
- // anything else is a real failure and must reach the global error handler.
761
- const refreshToken = 'valid-refresh-token';
762
- vi.mocked(authRepo.findRefreshToken).mockRejectedValue(new Error('DB error'));
763
-
764
- // Act & Assert
765
- await expect(authService.logout(refreshToken)).rejects.toThrow('DB error');
532
+ it('propagates database failures so a failed logout cannot report success', async () => {
533
+ vi.mocked(authRepo.revokeSession).mockRejectedValueOnce(new Error('DB error'));
534
+ await expect(authService.logout('refresh')).rejects.toThrow('DB error');
766
535
  });
767
536
  });
768
537
 
@@ -785,7 +554,7 @@ describe('Auth Service', () => {
785
554
  statusCode: 503,
786
555
  code: 'SERVICE_UNAVAILABLE',
787
556
  });
788
- expect(mockRedis.getdel).not.toHaveBeenCalled();
557
+ expect(mockRedis.get).not.toHaveBeenCalled();
789
558
  });
790
559
 
791
560
  it('forgotPassword still answers normally while Redis is connected (unknown email: no error)', async () => {
@@ -795,36 +564,30 @@ describe('Auth Service', () => {
795
564
  });
796
565
 
797
566
  describe('resetPassword', () => {
798
- it('consumes the token in one step (GETDEL), changes the password and ends all sessions', async () => {
799
- mockRedis.getdel.mockResolvedValue(testUsers.validUser.id);
567
+ it('commits recovery against the password observed before token consumption', async () => {
568
+ mockRedis.get.mockResolvedValue(testUsers.validUser.id);
569
+ mockRedis.eval.mockResolvedValue(1);
800
570
  vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
801
571
  vi.mocked(hashPassword).mockResolvedValue('new-hash');
572
+ vi.mocked(authRepo.commitPasswordRecovery).mockResolvedValue(true);
802
573
 
803
574
  await authService.resetPassword('reset-token', 'New-Passw0rd-123!');
804
575
 
805
- expect(mockRedis.getdel).toHaveBeenCalledTimes(1);
806
- expect(mockRedis.get).not.toHaveBeenCalled();
807
- expect(authRepo.updateUserPassword).toHaveBeenCalledWith(testUsers.validUser.id, 'new-hash');
808
- expect(mockRedis.del).toHaveBeenCalledWith(`pw-reset-user:${testUsers.validUser.id}`);
809
- expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(testUsers.validUser.id);
810
- expect(authRepo.deleteRefreshTokensByUserId).toHaveBeenCalledWith(testUsers.validUser.id);
576
+ expect(authRepo.commitPasswordRecovery).toHaveBeenCalledWith(
577
+ testUsers.validUser.id, testUsers.validUser.password, 'new-hash',
578
+ );
579
+ expect(mockRedis.del).not.toHaveBeenCalled();
811
580
  });
812
581
 
813
- it('the same link used twice at once changes the password only once', async () => {
814
- // Redis hands the token to the first GETDEL only.
815
- mockRedis.getdel.mockResolvedValueOnce(testUsers.validUser.id).mockResolvedValueOnce(null);
582
+ it('keeps the password unchanged when the token store refuses consumption', async () => {
583
+ mockRedis.get.mockResolvedValue(testUsers.validUser.id);
584
+ mockRedis.eval.mockResolvedValue(0);
816
585
  vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
817
- vi.mocked(hashPassword).mockResolvedValue('new-hash');
818
586
 
819
- const results = await Promise.allSettled([
820
- authService.resetPassword('reset-token', 'New-Passw0rd-123!'),
821
- authService.resetPassword('reset-token', 'New-Passw0rd-123!'),
822
- ]);
823
-
824
- expect(results.map((r) => r.status).sort()).toEqual(['fulfilled', 'rejected']);
825
- const rejected = results.find((r) => r.status === 'rejected') as PromiseRejectedResult;
826
- expect(rejected.reason).toMatchObject({ statusCode: 400, code: 'INVALID_RESET_TOKEN' });
827
- expect(authRepo.updateUserPassword).toHaveBeenCalledTimes(1);
587
+ await expect(authService.resetPassword('reset-token', 'New-Passw0rd-123!')).rejects.toMatchObject({
588
+ statusCode: 400, code: 'INVALID_RESET_TOKEN',
589
+ });
590
+ expect(authRepo.commitPasswordRecovery).not.toHaveBeenCalled();
828
591
  });
829
592
  });
830
593
 
@@ -0,0 +1,177 @@
1
+ import { afterAll, beforeAll, expect, it } from 'vitest';
2
+ import type { FastifyInstance } from 'fastify';
3
+ import { createHash } from 'node:crypto';
4
+ import { buildTestApp, db, PASSWORD, redis, startEmailStub, tokenOf, uniqueEmail, type EmailStub } from '@/test/integration-helpers.js';
5
+
6
+ let app: FastifyInstance;
7
+ let mail: EmailStub;
8
+ let origin: string;
9
+ const client = 'https://recovery-client.example.test';
10
+ const newPassword = 'New-Fixture-Passw0rd-42';
11
+ const verification = process.env.TIGRA_LIVE_VERIFICATION === 'true';
12
+ const fingerprint = (token: string): string => createHash('sha256').update(token).digest('hex');
13
+
14
+ interface AuthResponse {
15
+ status: number;
16
+ data: { data?: { user?: { id: string }; id?: string }; error?: { code: string } };
17
+ cookies: string;
18
+ }
19
+
20
+ beforeAll(async () => {
21
+ process.env.CLIENT_URL = client;
22
+ process.env.REQUIRE_USER_VERIFICATION = String(verification);
23
+ process.env.RATE_LIMIT_ENABLED = 'true';
24
+ mail = await startEmailStub();
25
+ app = await buildTestApp();
26
+ origin = await app.listen({ host: '127.0.0.1', port: 0 });
27
+ });
28
+
29
+ afterAll(async () => {
30
+ await app?.close();
31
+ await mail?.close();
32
+ });
33
+
34
+ async function request(route: string, body?: object, cookie?: string): Promise<AuthResponse> {
35
+ const response = await fetch(`${origin}/api/v1/auth/${route}`, {
36
+ method: body === undefined ? 'GET' : 'POST',
37
+ headers: {
38
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
39
+ ...(cookie ? { cookie } : {}),
40
+ },
41
+ body: body === undefined ? undefined : JSON.stringify(body),
42
+ });
43
+ const data = await response.json() as AuthResponse['data'];
44
+ const cookies = response.headers.getSetCookie().map(value => value.split(';', 1)[0]).join('; ');
45
+ return { status: response.status, data, cookies };
46
+ }
47
+
48
+ async function register(tag: string): Promise<{ email: string; cookies: string; id?: string }> {
49
+ const email = uniqueEmail(tag);
50
+ const registration = await request('register', { email, password: PASSWORD, firstName: 'Test', lastName: 'User' });
51
+ expect(registration.status).toBe(201);
52
+ if (!verification) return { email, cookies: registration.cookies, id: registration.data.data?.user?.id };
53
+ const inbox = await mail.waitFor(email, entry => Boolean(entry.link?.includes('/verify-account')));
54
+ const result = await request('verify-account', { token: tokenOf(inbox[0]?.link ?? null) });
55
+ expect(result.status).toBe(200);
56
+ return { email, cookies: result.cookies, id: registration.data.data?.user?.id };
57
+ }
58
+
59
+ const isResetMail = (entry: { link: string | null }): boolean => Boolean(entry.link?.includes('/reset-password'));
60
+
61
+ async function resetMail(email: string, count: number): Promise<string> {
62
+ const messages = await mail.waitFor(email, isResetMail, count);
63
+ expect(messages.length).toBe(count);
64
+ const message = messages.at(-1)!;
65
+ expect(message.to).toBe(email);
66
+ const url = new URL(message.link!);
67
+ expect(url.origin).toBe(client);
68
+ expect(url.pathname).toBe('/reset-password');
69
+ return tokenOf(url.href);
70
+ }
71
+
72
+ it('keeps recovery scoped to the recipient and invalidates old credentials after commit', async () => {
73
+ const account = await register('recover');
74
+ const other = await register('unrelated');
75
+ const secondLogin = await request('login', { email: account.email, password: PASSWORD });
76
+ expect(secondLogin.status).toBe(200);
77
+ expect((await request('forgot-password', { email: account.email })).status).toBe(200);
78
+ const first = await resetMail(account.email, 1);
79
+ expect((await request('forgot-password', { email: account.email })).status).toBe(200);
80
+ const latest = await resetMail(account.email, 2);
81
+ const cache = await redis();
82
+ expect(await cache.exists('pw-reset:' + fingerprint(first))).toBe(0);
83
+ expect(await cache.ttl('pw-reset:' + fingerprint(latest))).toBeGreaterThan(3_580);
84
+ expect((await request('reset-password', { token: first, newPassword })).status).toBe(400);
85
+
86
+ // Refresh rows from before session tracking have no session to cascade from.
87
+ const database = await db();
88
+ const legacy = await database.refreshToken.create({
89
+ data: {
90
+ token: fingerprint(uniqueEmail('legacy-refresh')),
91
+ userId: account.id!,
92
+ expiresAt: new Date(Date.now() + 60_000),
93
+ },
94
+ });
95
+ const results = await Promise.all([
96
+ request('reset-password', { token: latest, newPassword }),
97
+ request('reset-password', { token: latest, newPassword }),
98
+ ]);
99
+ expect(results.map(result => result.status).sort()).toEqual([200, 400]);
100
+ expect(await database.refreshToken.findUnique({ where: { id: legacy.id } })).toBeNull();
101
+ expect((await request('reset-password', { token: latest, newPassword })).status).toBe(400);
102
+ expect((await request('me', undefined, account.cookies)).status).toBe(401);
103
+ expect((await request('refresh', {}, secondLogin.cookies)).status).toBe(401);
104
+ expect((await request('login', { email: account.email, password: PASSWORD })).status).toBe(401);
105
+ const recovered = await request('login', { email: account.email, password: newPassword });
106
+ expect(recovered.data.data?.user?.id).toBe(account.id);
107
+ expect((await request('me', undefined, other.cookies)).data.data?.id).toBe(other.id);
108
+ });
109
+
110
+ it('rejects an expired recovery record', async () => {
111
+ const account = await register('expiry');
112
+ expect((await request('forgot-password', { email: account.email })).status).toBe(200);
113
+ const token = await resetMail(account.email, 1);
114
+ const cache = await redis();
115
+ await cache.pexpire('pw-reset:' + fingerprint(token), 1);
116
+ await expect.poll(() => cache.exists('pw-reset:' + fingerprint(token))).toBe(0);
117
+ const result = await request('reset-password', { token, newPassword });
118
+ expect([result.status, result.data.error?.code]).toEqual([400, 'INVALID_RESET_TOKEN']);
119
+ });
120
+
121
+ it('honors a current link issued before the upgrade', async () => {
122
+ const account = await register('legacy');
123
+ // The pre-upgrade store held a fingerprint-to-user entry and a matching pointer.
124
+ const token = 'legacy-reset-fixture';
125
+ const key = fingerprint(token);
126
+ const cache = await redis();
127
+ await cache.set('pw-reset:' + key, account.id!, 'EX', 60);
128
+ await cache.set('pw-reset-user:' + account.id, key, 'EX', 60);
129
+ const result = await request('reset-password', { token, newPassword });
130
+ expect(result.status).toBe(200);
131
+ expect(await cache.exists('pw-reset:' + key, 'pw-reset-user:' + account.id)).toBe(0);
132
+ });
133
+
134
+ it('keeps a later issuance current when older work resumes', async () => {
135
+ const { issueRecoveryToken } = await import('../recovery.store.js');
136
+ const account = await register('ordering');
137
+ const latest = 'latest-test-fixture';
138
+ const userId = account.id!;
139
+ await expect(issueRecoveryToken(userId, latest, '200-0')).resolves.toBe(true);
140
+ await expect(issueRecoveryToken(userId, 'older-test-fixture', '150-2')).resolves.toBe(false);
141
+ expect(await (await redis()).get('pw-reset-user:' + userId)).toBe(fingerprint(latest));
142
+ expect((await request('reset-password', { token: latest, newPassword })).status).toBe(200);
143
+ await expect(issueRecoveryToken(userId, latest, '200-0')).resolves.toBe(false);
144
+ });
145
+
146
+ it('shares quota across address casing and keeps the original registration', async () => {
147
+ const account = await register('quota');
148
+ const duplicate = await request('register', {
149
+ email: account.email.toUpperCase(), password: newPassword, firstName: 'Test', lastName: 'User',
150
+ });
151
+ expect(duplicate.status).toBe(409);
152
+ expect((await request('login', { email: account.email, password: PASSWORD })).data.data?.user?.id).toBe(account.id);
153
+ for (const email of [account.email, account.email.toUpperCase(), account.email]) {
154
+ expect((await request('forgot-password', { email })).status).toBe(200);
155
+ }
156
+ const refused = await request('forgot-password', { email: account.email.toUpperCase() });
157
+ expect([refused.status, refused.data.error?.code]).toEqual([429, 'EMAIL_RATE_LIMITED']);
158
+ await resetMail(account.email, 3);
159
+ });
160
+
161
+ it('acknowledges known and unknown recovery before a slow local provider responds', async () => {
162
+ const account = await register('slow-mail');
163
+ const unknown = uniqueEmail('unknown');
164
+ mail.respond({ delayMs: 3_000 });
165
+ const started = performance.now();
166
+ const [known, absent] = await Promise.all([
167
+ request('forgot-password', { email: account.email }),
168
+ request('forgot-password', { email: unknown }),
169
+ ]);
170
+ expect(performance.now() - started).toBeLessThan(2_000);
171
+ expect(known.status).toBe(200);
172
+ expect(absent.status).toBe(200);
173
+ expect(known.data).toEqual(absent.data);
174
+ await resetMail(account.email, 1);
175
+ expect(mail.to(unknown)).toHaveLength(0);
176
+ mail.respond({});
177
+ });