create-tigra 4.1.0 → 5.0.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 (140) hide show
  1. package/CHANGELOG.md +16 -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/src/features/auth/components/AuthInitializer.tsx +45 -7
  31. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  32. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  33. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  34. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  35. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  36. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  37. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  38. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  39. package/template/client/src/lib/api/axios.config.ts +24 -6
  40. package/template/client/src/lib/api/session-events.ts +54 -0
  41. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  42. package/template/client/src/store/__tests__/store.test.ts +1 -0
  43. package/template/gitignore +3 -2
  44. package/template/server/.dockerignore +2 -5
  45. package/template/server/.env.example +1 -0
  46. package/template/server/.env.example.production +1 -0
  47. package/template/server/README.md +7 -2
  48. package/template/server/docs/deployment.md +66 -0
  49. package/template/server/docs/logging.md +9 -8
  50. package/template/server/docs/rate-limits.md +6 -4
  51. package/template/server/gitignore +33 -0
  52. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  53. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  54. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  55. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  56. package/template/server/prisma/schema.prisma +25 -1
  57. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  58. package/template/server/src/app.ts +14 -5
  59. package/template/server/src/config/env.ts +8 -0
  60. package/template/server/src/config/rate-limit.config.ts +1 -1
  61. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  62. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  63. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  64. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  65. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  66. package/template/server/src/jobs/index.ts +8 -2
  67. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  68. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  69. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  70. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  71. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  72. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  73. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  74. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  75. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  76. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  77. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  78. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  79. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  80. package/template/server/src/libs/account-mutation.ts +77 -0
  81. package/template/server/src/libs/auth.ts +37 -3
  82. package/template/server/src/libs/cookies.ts +25 -13
  83. package/template/server/src/libs/email-quota.ts +11 -7
  84. package/template/server/src/libs/email.ts +11 -8
  85. package/template/server/src/libs/error-handler.ts +16 -12
  86. package/template/server/src/libs/http.ts +37 -13
  87. package/template/server/src/libs/ip-block.ts +56 -34
  88. package/template/server/src/libs/logger.ts +23 -8
  89. package/template/server/src/libs/monitoring.ts +57 -31
  90. package/template/server/src/libs/observability/sentry.ts +65 -49
  91. package/template/server/src/libs/prisma.ts +1 -1
  92. package/template/server/src/libs/private-cache.ts +6 -0
  93. package/template/server/src/libs/rate-limiting.ts +4 -0
  94. package/template/server/src/libs/requestLogger.ts +3 -3
  95. package/template/server/src/libs/safe-http.ts +58 -18
  96. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  97. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  98. package/template/server/src/libs/storage/file-validator.ts +2 -1
  99. package/template/server/src/libs/url-safety.ts +10 -2
  100. package/template/server/src/libs/validation-errors.ts +11 -8
  101. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  102. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  103. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  104. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  105. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  106. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  107. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  108. package/template/server/src/modules/admin/admin.service.ts +61 -62
  109. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  110. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  111. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  112. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  113. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  114. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  115. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  116. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  117. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  118. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  119. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  120. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  121. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  122. package/template/server/src/modules/auth/auth.service.ts +33 -237
  123. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  124. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  125. package/template/server/src/modules/auth/session.repo.ts +5 -4
  126. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  127. package/template/server/src/modules/files/files.controller.ts +2 -2
  128. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  129. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  130. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  131. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  132. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  133. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  134. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  135. package/template/server/src/modules/users/users.controller.ts +28 -25
  136. package/template/server/src/modules/users/users.repo.ts +12 -51
  137. package/template/server/src/modules/users/users.service.ts +109 -234
  138. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  139. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  140. package/template/server/src/test/setup.ts +4 -0
@@ -6,10 +6,12 @@
6
6
 
7
7
  import { logger } from '@libs/logger.js';
8
8
  import { NotFoundError, ForbiddenError, ConflictError } from '@shared/errors/errors.js';
9
- import { RETENTION_DAYS } from '@/jobs/cleanup-deleted-accounts.job.js';
9
+ import { RETENTION_MS } from '@/jobs/cleanup-deleted-accounts.job.js';
10
10
  import { adminRepository } from './admin.repo.js';
11
- import { sessionRepository } from '@modules/auth/session.repo.js';
12
- import { deleteRefreshTokensByUserId } from '@modules/auth/auth.repo.js';
11
+ import {
12
+ assertAnotherSignInAdmin, assertMutationActor, revokeAccountCredentials, runAccountMutation,
13
+ type MutationActor,
14
+ } from '@libs/account-mutation.js';
13
15
 
14
16
  import type { UserRole } from '@shared/types/index.js';
15
17
  import type { AdminUser, AdminUserDetail, AdminSession, DashboardStats } from './admin.repo.js';
@@ -35,7 +37,7 @@ class AdminService {
35
37
  ...result,
36
38
  items: result.items.map((user) => ({
37
39
  ...user,
38
- purgeAt: new Date(user.deletedAt!.getTime() + RETENTION_DAYS * 24 * 60 * 60 * 1000),
40
+ purgeAt: new Date(user.deletedAt!.getTime() + RETENTION_MS),
39
41
  })),
40
42
  };
41
43
  }
@@ -49,17 +51,25 @@ class AdminService {
49
51
  *
50
52
  * @throws NotFoundError 404 USER_NOT_FOUND if the account does not exist (or was purged)
51
53
  * @throws ConflictError 409 USER_NOT_DELETED if the account is not deleted
54
+ * @throws ConflictError 409 USER_PURGE_IN_PROGRESS once a purge has claimed the account
52
55
  */
53
- async restoreUser(userId: string): Promise<AdminUser> {
54
- if (!(await adminRepository.restoreUser(userId))) {
55
- if (!(await adminRepository.userExists(userId))) {
56
- throw new NotFoundError('User not found', 'USER_NOT_FOUND');
56
+ async restoreUser(userId: string, actor: MutationActor): Promise<AdminUser> {
57
+ const user = await runAccountMutation(async tx => {
58
+ await assertMutationActor(tx, actor, 'ADMIN');
59
+ if (!(await adminRepository.restoreUser(tx, userId))) {
60
+ const state = await adminRepository.getPurgeState(tx, userId);
61
+ if (!state) {
62
+ throw new NotFoundError('User not found', 'USER_NOT_FOUND');
63
+ }
64
+ if (state.purgeStartedAt) {
65
+ throw new ConflictError('Permanent deletion has already started for this account.', 'USER_PURGE_IN_PROGRESS');
66
+ }
67
+ throw new ConflictError('This account is not deleted', 'USER_NOT_DELETED');
57
68
  }
58
- throw new ConflictError('This account is not deleted', 'USER_NOT_DELETED');
59
- }
60
-
61
- const user = await adminRepository.findUserById(userId);
62
- if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
69
+ const restored = await adminRepository.findUserById(tx, userId);
70
+ if (!restored) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
71
+ return restored;
72
+ });
63
73
 
64
74
  logger.info({ msg: 'Deleted account restored', userId });
65
75
  return user;
@@ -87,25 +97,22 @@ class AdminService {
87
97
  * An admin can never ban themselves (like changing their own role): it would
88
98
  * end their own sessions and could leave the project with no admin at all.
89
99
  */
90
- async toggleUserStatus(userId: string, isActive: boolean, adminUserId: string): Promise<AdminUser> {
91
- if (!isActive && userId === adminUserId) {
100
+ async toggleUserStatus(userId: string, isActive: boolean, actor: MutationActor): Promise<AdminUser> {
101
+ if (!isActive && userId === actor.userId) {
92
102
  throw new ForbiddenError('You cannot ban your own account', 'CANNOT_BAN_SELF');
93
103
  }
94
104
 
95
- const user = await adminRepository.findUserById(userId);
96
-
97
- if (!user) {
98
- throw new NotFoundError('User not found');
99
- }
100
-
101
- const approveEmail = isActive && !user.emailVerifiedAt;
102
- const updatedUser = await adminRepository.updateUserStatus(userId, isActive, approveEmail);
105
+ const { updatedUser, deletedSessions } = await runAccountMutation(async tx => {
106
+ await assertMutationActor(tx, actor, 'ADMIN');
107
+ const user = await adminRepository.findUserById(tx, userId);
108
+ if (!user) throw new NotFoundError('User not found');
109
+ if (!isActive) await assertAnotherSignInAdmin(tx, user);
110
+ const updatedUser = await adminRepository.updateUserStatus(tx, userId, isActive, isActive && !user.emailVerifiedAt);
111
+ const deletedSessions = isActive ? 0 : await revokeAccountCredentials(tx, userId);
112
+ return { updatedUser, deletedSessions };
113
+ });
103
114
 
104
115
  if (!isActive) {
105
- // Force-logout: invalidate all sessions and refresh tokens
106
- const deletedSessions = await sessionRepository.deleteAllUserSessions(userId);
107
- await deleteRefreshTokensByUserId(userId);
108
-
109
116
  logger.info({
110
117
  msg: 'User deactivated and sessions invalidated',
111
118
  userId,
@@ -125,25 +132,25 @@ class AdminService {
125
132
  async changeUserRole(
126
133
  userId: string,
127
134
  role: UserRole,
128
- adminUserId: string,
135
+ actor: MutationActor,
129
136
  ): Promise<AdminUser> {
130
- if (userId === adminUserId) {
137
+ if (userId === actor.userId) {
131
138
  throw new ForbiddenError('Cannot change your own role');
132
139
  }
133
140
 
134
- const user = await adminRepository.findUserById(userId);
135
-
136
- if (!user) {
137
- throw new NotFoundError('User not found');
138
- }
139
-
140
- const updatedUser = await adminRepository.updateUserRole(userId, role);
141
+ const { updatedUser, deletedSessions } = await runAccountMutation(async tx => {
142
+ await assertMutationActor(tx, actor, 'ADMIN');
143
+ const user = await adminRepository.findUserById(tx, userId);
144
+ if (!user) throw new NotFoundError('User not found');
145
+ const demotion = user.role === 'ADMIN' && role === 'USER';
146
+ if (demotion) await assertAnotherSignInAdmin(tx, user);
147
+ const updatedUser = await adminRepository.updateUserRole(tx, userId, role);
148
+ const deletedSessions = demotion ? await revokeAccountCredentials(tx, userId) : undefined;
149
+ return { updatedUser, deletedSessions };
150
+ });
141
151
 
142
152
  // If demoting from ADMIN to USER, invalidate sessions so new role takes effect
143
- if (user.role === 'ADMIN' && role === 'USER') {
144
- const deletedSessions = await sessionRepository.deleteAllUserSessions(userId);
145
- await deleteRefreshTokensByUserId(userId);
146
-
153
+ if (deletedSessions !== undefined) {
147
154
  logger.info({
148
155
  msg: 'User demoted from ADMIN and sessions invalidated',
149
156
  userId,
@@ -167,13 +174,15 @@ class AdminService {
167
174
  */
168
175
  async promoteToAdmin(rawEmail: string): Promise<'promoted' | 'already-admin' | 'not-found' | 'deleted' | 'banned'> {
169
176
  const email = rawEmail.trim().toLowerCase(); // register stores emails lower-cased
170
- const account = await adminRepository.findAccountStateByEmail(email);
171
- if (!account) return 'not-found';
172
- if (account.deletedAt) return 'deleted';
173
- if (!account.isActive) return 'banned';
174
- if (account.role === 'ADMIN') return 'already-admin';
175
- await adminRepository.promoteToAdmin(account.id, account.emailVerifiedAt ?? new Date());
176
- return 'promoted';
177
+ return runAccountMutation(async tx => {
178
+ const account = await adminRepository.findAccountStateByEmail(tx, email);
179
+ if (!account) return 'not-found';
180
+ if (account.deletedAt) return 'deleted';
181
+ if (!account.isActive) return 'banned';
182
+ if (account.role === 'ADMIN') return 'already-admin';
183
+ await adminRepository.promoteToAdmin(tx, account.id, account.emailVerifiedAt ?? new Date());
184
+ return 'promoted';
185
+ });
177
186
  }
178
187
 
179
188
  /**
@@ -198,22 +207,12 @@ class AdminService {
198
207
  * Force-expire a specific session.
199
208
  * Deletes the session and any associated refresh tokens.
200
209
  */
201
- async forceExpireSession(sessionId: string): Promise<void> {
202
- const session = await adminRepository.getSessionById(sessionId);
203
-
204
- if (!session) {
205
- throw new NotFoundError('Session not found');
206
- }
207
-
208
- // Delete refresh tokens linked to this session first
209
- await adminRepository.deleteRefreshTokensBySessionId(sessionId);
210
- await adminRepository.deleteSession(sessionId);
211
-
212
- logger.info({
213
- msg: 'Session force-expired by admin',
214
- sessionId,
215
- userId: session.userId,
210
+ async forceExpireSession(sessionId: string, actor: MutationActor): Promise<void> {
211
+ await runAccountMutation(async tx => {
212
+ await assertMutationActor(tx, actor, 'ADMIN');
213
+ if (!await adminRepository.deleteLiveSession(tx, sessionId)) throw new NotFoundError('Session not found');
216
214
  });
215
+ logger.info({ msg: 'Session force-expired by admin', sessionId, adminUserId: actor.userId });
217
216
  }
218
217
  }
219
218
 
@@ -0,0 +1,12 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { loginSchema, registerSchema } from '../auth.schemas.js';
3
+
4
+ describe('account email validation', () => {
5
+ const credentials = { password: 'FixturePassword1', firstName: 'Test', lastName: 'User' };
6
+ const email = (lastLabelLength: number): string => `${'a'.repeat(60)}@${'b'.repeat(63)}.${'c'.repeat(lastLabelLength)}.test`;
7
+
8
+ it.each([registerSchema, loginSchema])('enforces the database length before lookup or persistence', (schema) => {
9
+ expect(schema.safeParse({ ...credentials, email: email(61) }).success).toBe(true);
10
+ expect(schema.safeParse({ ...credentials, email: email(62) }).success).toBe(false);
11
+ });
12
+ });
@@ -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