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
@@ -6,48 +6,64 @@
6
6
  import { describe, expect, it, vi, beforeEach } from 'vitest';
7
7
  import { usersService } from '../users.service.js';
8
8
  import * as authRepo from '@modules/auth/auth.repo.js';
9
- import { sessionRepository } from '@modules/auth/session.repo.js';
10
9
  import { usersRepository } from '../users.repo.js';
11
10
  import { hashPassword, verifyPassword } from '@libs/password.js';
12
- import { fileStorageService } from '@libs/storage/file-storage.service.js';
11
+ import { queueReplacedAvatar, tryAvatarCleanup } from '../avatar-cleanup.js';
13
12
  import { testUsers } from '@/test/setup.js';
13
+ import { prisma } from '@libs/prisma.js';
14
+ import { env } from '@config/env.js';
15
+
16
+ const tx = vi.hoisted(() => ({
17
+ user: { findUnique: vi.fn(), count: vi.fn(), update: vi.fn() },
18
+ session: { findFirst: vi.fn(), deleteMany: vi.fn() },
19
+ refreshToken: { deleteMany: vi.fn() },
20
+ }));
14
21
 
15
22
  vi.mock('@modules/auth/auth.repo.js');
16
- vi.mock('@modules/auth/session.repo.js');
23
+ vi.mock('@libs/prisma.js', () => ({ prisma: { $transaction: vi.fn() }, isPrismaWriteConflict: vi.fn() }));
17
24
  vi.mock('../users.repo.js');
18
25
  vi.mock('@libs/password.js');
19
- vi.mock('@libs/storage/file-storage.service.js', () => ({ fileStorageService: { deleteAvatar: vi.fn() } }));
26
+ vi.mock('../avatar-cleanup.js');
20
27
  vi.mock('@libs/storage/image-optimizer.service.js', () => ({ imageOptimizerService: {} }));
21
28
 
22
29
  const user = testUsers.validUser;
30
+ const actor = { userId: user.id, sessionId: 'session-here' };
31
+ const avatar = { userId: user.id, filename: 'avatar-fixture.webp' };
23
32
 
24
33
  describe('users.service password confirmation', () => {
25
34
  beforeEach(() => {
26
35
  vi.clearAllMocks();
27
36
  vi.mocked(authRepo.findUserById).mockResolvedValue(user);
37
+ vi.mocked(authRepo.lockUser).mockResolvedValue(user);
38
+ vi.mocked(prisma.$transaction).mockImplementation(write => write(tx as never));
39
+ tx.user.findUnique.mockResolvedValue(user);
40
+ tx.user.count.mockResolvedValue(0);
41
+ tx.session.findFirst.mockResolvedValue({ id: actor.sessionId });
42
+ tx.session.deleteMany.mockResolvedValue({ count: 1 });
28
43
  vi.mocked(hashPassword).mockResolvedValue('new-hash');
44
+ vi.mocked(queueReplacedAvatar).mockResolvedValue(null);
29
45
  });
30
46
 
31
47
  it('changePassword with a wrong current password answers 422 INVALID_CURRENT_PASSWORD and changes nothing', async () => {
32
48
  vi.mocked(verifyPassword).mockResolvedValue(false);
33
49
  await expect(
34
- usersService.changePassword(user.id, { currentPassword: 'wrong', newPassword: 'New-Passw0rd-123!' }),
50
+ usersService.changePassword(user.id, { currentPassword: 'wrong', newPassword: 'New-Passw0rd-123!' }, actor),
35
51
  ).rejects.toMatchObject({ statusCode: 422, code: 'INVALID_CURRENT_PASSWORD', message: 'Current password is incorrect' });
36
- expect(authRepo.updateUserPassword).not.toHaveBeenCalled();
37
- expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
52
+ expect(tx.user.update).not.toHaveBeenCalled();
53
+ expect(tx.session.deleteMany).not.toHaveBeenCalled();
38
54
  });
39
55
 
40
- it('changePassword with the right current password still changes it and ends all sessions', async () => {
56
+ it('changes the password through the transaction and retains just the requesting session', async () => {
41
57
  // First call: current password matches; second: the new one differs from it.
42
58
  vi.mocked(verifyPassword).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
43
- await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' });
44
- expect(authRepo.updateUserPassword).toHaveBeenCalledWith(user.id, 'new-hash');
45
- expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(user.id);
59
+ await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' }, actor);
60
+ expect(tx.user.update).toHaveBeenCalledWith({ where: { id: user.id }, data: { password: 'new-hash' } });
61
+ expect(tx.session.deleteMany).toHaveBeenCalledWith({ where: { userId: user.id, id: { not: actor.sessionId } } });
46
62
  });
47
63
 
48
64
  it('deleteAccount with a wrong password answers 422 INVALID_PASSWORD and deletes nothing', async () => {
49
65
  vi.mocked(verifyPassword).mockResolvedValue(false);
50
- await expect(usersService.deleteAccount(user.id, 'wrong')).rejects.toMatchObject({
66
+ await expect(usersService.deleteAccount(user.id, actor, 'wrong')).rejects.toMatchObject({
51
67
  statusCode: 422,
52
68
  code: 'INVALID_PASSWORD',
53
69
  message: 'Incorrect password',
@@ -57,73 +73,129 @@ describe('users.service password confirmation', () => {
57
73
 
58
74
  it('deleteAccount with the right password still soft-deletes and ends all sessions', async () => {
59
75
  vi.mocked(verifyPassword).mockResolvedValue(true);
60
- await usersService.deleteAccount(user.id, 'right');
61
- expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(user.id);
62
- expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(user.id);
76
+ await usersService.deleteAccount(user.id, actor, 'right');
77
+ expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(tx, user.id);
78
+ expect(tx.session.deleteMany).toHaveBeenCalledWith({ where: { userId: user.id } });
63
79
  });
64
80
 
65
81
  it('deleteAccount removes the public avatar at once, after the soft delete', async () => {
66
82
  vi.mocked(verifyPassword).mockResolvedValue(true);
67
- await usersService.deleteAccount(user.id, 'right');
68
- expect(fileStorageService.deleteAvatar).toHaveBeenCalledWith(user.id);
83
+ vi.mocked(queueReplacedAvatar).mockResolvedValueOnce(avatar);
84
+ await usersService.deleteAccount(user.id, actor, 'right');
85
+ expect(tryAvatarCleanup).toHaveBeenCalledWith(avatar);
69
86
  const softDeletedAt = vi.mocked(usersRepository.softDeleteUser).mock.invocationCallOrder[0];
70
- expect(vi.mocked(fileStorageService.deleteAvatar).mock.invocationCallOrder[0]).toBeGreaterThan(softDeletedAt);
87
+ expect(vi.mocked(tryAvatarCleanup).mock.invocationCallOrder[0]).toBeGreaterThan(softDeletedAt);
71
88
  });
72
89
 
73
90
  it('an admin deleting an account removes its public avatar too', async () => {
74
- await usersService.deleteAccount(user.id, '', true);
75
- expect(fileStorageService.deleteAvatar).toHaveBeenCalledWith(user.id);
76
- });
77
-
78
- it('deleteAccount still succeeds when the avatar file cannot be removed (the purge retries)', async () => {
79
- vi.mocked(verifyPassword).mockResolvedValue(true);
80
- vi.mocked(fileStorageService.deleteAvatar).mockRejectedValueOnce(new Error('disk'));
81
- await expect(usersService.deleteAccount(user.id, 'right')).resolves.toBeUndefined();
82
- expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(user.id);
91
+ const admin = { userId: 'admin-user', sessionId: 'admin-session' };
92
+ tx.user.findUnique.mockResolvedValueOnce({ ...user, id: admin.userId, role: 'ADMIN' });
93
+ vi.mocked(queueReplacedAvatar).mockResolvedValueOnce(avatar);
94
+ await usersService.deleteAccount(user.id, admin);
95
+ expect(tryAvatarCleanup).toHaveBeenCalledWith(avatar);
83
96
  });
84
97
 
85
98
  it("an owner's password change keeps the asking device signed in and ends every other session", async () => {
86
99
  vi.mocked(verifyPassword).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
87
- await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' }, false, 'session-here');
88
- expect(sessionRepository.deleteOtherUserSessions).toHaveBeenCalledWith(user.id, 'session-here');
89
- expect(authRepo.deleteRefreshTokensByUserId).toHaveBeenCalledWith(user.id, { exceptSessionId: 'session-here' });
90
- expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
100
+ await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' }, actor);
101
+ expect(tx.refreshToken.deleteMany).toHaveBeenCalledWith({ where: {
102
+ userId: user.id, OR: [{ sessionId: null }, { sessionId: { not: actor.sessionId } }],
103
+ } });
91
104
  });
92
105
 
93
106
  it('an admin-forced password change still ends every session of that user', async () => {
94
107
  vi.mocked(verifyPassword).mockResolvedValue(false); // only the "same as current" check runs
95
- await usersService.changePassword(user.id, { newPassword: 'New-Passw0rd-123!' }, true, 'admins-own-session');
96
- expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(user.id);
97
- expect(authRepo.deleteRefreshTokensByUserId).toHaveBeenCalledWith(user.id);
98
- expect(sessionRepository.deleteOtherUserSessions).not.toHaveBeenCalled();
108
+ tx.user.findUnique.mockResolvedValueOnce({ ...user, role: 'ADMIN' });
109
+ await usersService.changePassword(user.id, { newPassword: 'New-Passw0rd-123!' }, {
110
+ userId: 'admin', sessionId: 'admins-own-session',
111
+ });
112
+ expect(tx.session.deleteMany).toHaveBeenCalledWith({ where: { userId: user.id } });
113
+ expect(tx.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { userId: user.id } });
99
114
  });
100
115
 
101
116
  it('the last active admin cannot delete their own account (409 LAST_ADMIN), and nothing is deleted', async () => {
102
117
  vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
118
+ tx.user.findUnique.mockResolvedValue({ ...user, role: 'ADMIN' });
103
119
  vi.mocked(verifyPassword).mockResolvedValue(true);
104
- vi.mocked(usersRepository.countOtherActiveAdmins).mockResolvedValue(0);
105
- await expect(usersService.deleteAccount(user.id, 'right')).rejects.toMatchObject({ statusCode: 409, code: 'LAST_ADMIN' });
120
+ await expect(usersService.deleteAccount(user.id, actor, 'right')).rejects.toMatchObject({ statusCode: 409, code: 'LAST_ADMIN' });
106
121
  expect(usersRepository.softDeleteUser).not.toHaveBeenCalled();
107
122
  });
108
123
 
109
124
  it('an admin can delete their own account when another active admin exists', async () => {
110
125
  vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
126
+ tx.user.findUnique.mockResolvedValue({ ...user, role: 'ADMIN' });
111
127
  vi.mocked(verifyPassword).mockResolvedValue(true);
112
- vi.mocked(usersRepository.countOtherActiveAdmins).mockResolvedValue(1);
113
- await usersService.deleteAccount(user.id, 'right');
114
- expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(user.id);
128
+ tx.user.count.mockResolvedValue(1);
129
+ await usersService.deleteAccount(user.id, actor, 'right');
130
+ expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(tx, user.id);
115
131
  });
116
132
 
117
133
  it('a wrong password still answers 422 first, even for the last admin', async () => {
118
134
  vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
119
135
  vi.mocked(verifyPassword).mockResolvedValue(false);
120
- await expect(usersService.deleteAccount(user.id, 'wrong')).rejects.toMatchObject({ code: 'INVALID_PASSWORD' });
121
- expect(usersRepository.countOtherActiveAdmins).not.toHaveBeenCalled();
136
+ await expect(usersService.deleteAccount(user.id, actor, 'wrong')).rejects.toMatchObject({ code: 'INVALID_PASSWORD' });
137
+ expect(tx.user.count).not.toHaveBeenCalled();
122
138
  });
123
139
 
124
140
  it('a normal user never triggers the admin check', async () => {
125
141
  vi.mocked(verifyPassword).mockResolvedValue(true);
126
- await usersService.deleteAccount(user.id, 'right');
127
- expect(usersRepository.countOtherActiveAdmins).not.toHaveBeenCalled();
142
+ await usersService.deleteAccount(user.id, actor, 'right');
143
+ expect(tx.user.count).not.toHaveBeenCalled();
144
+ });
145
+
146
+ it('checks that the password hash still matches inside the write transaction', async () => {
147
+ vi.mocked(verifyPassword).mockResolvedValue(true);
148
+ tx.user.findUnique.mockResolvedValue({ ...user, password: 'changed' });
149
+ await expect(usersService.deleteAccount(user.id, actor, 'right')).rejects.toMatchObject({ code: 'INVALID_PASSWORD' });
150
+ expect(usersRepository.softDeleteUser).not.toHaveBeenCalled();
151
+ });
152
+
153
+ it('only counts verified admins toward the last-admin rule when verification is required', async () => {
154
+ const requireVerification = env.REQUIRE_USER_VERIFICATION;
155
+ try {
156
+ env.REQUIRE_USER_VERIFICATION = true;
157
+ tx.user.findUnique.mockResolvedValue({ ...user, role: 'ADMIN', emailVerifiedAt: new Date() });
158
+ vi.mocked(verifyPassword).mockResolvedValue(true);
159
+ await expect(usersService.deleteAccount(user.id, actor, 'right')).rejects.toMatchObject({ code: 'LAST_ADMIN' });
160
+ expect(tx.user.count).toHaveBeenCalledWith({ where: {
161
+ id: { not: user.id }, role: 'ADMIN', isActive: true, deletedAt: null, emailVerifiedAt: { not: null },
162
+ } });
163
+ } finally {
164
+ env.REQUIRE_USER_VERIFICATION = requireVerification;
165
+ }
166
+ });
167
+ });
168
+
169
+ describe('profile and avatar authorization at write time', () => {
170
+ const operator = { userId: 'admin-user', sessionId: 'admin-session' };
171
+
172
+ beforeEach(() => {
173
+ vi.clearAllMocks();
174
+ vi.mocked(prisma.$transaction).mockImplementation(write => write(tx as never));
175
+ tx.user.findUnique.mockResolvedValue(user);
176
+ tx.session.findFirst.mockResolvedValue({ id: actor.sessionId });
177
+ vi.mocked(usersRepository.getUserById).mockResolvedValue(user);
178
+ vi.mocked(usersRepository.updateUserProfile).mockResolvedValue(user);
179
+ });
180
+
181
+ it('rejects a pending profile write when the actor session is gone', async () => {
182
+ tx.session.findFirst.mockResolvedValueOnce(null);
183
+ await expect(usersService.updateProfile(user.id, { firstName: 'Updated' }, actor))
184
+ .rejects.toMatchObject({ statusCode: 401, code: 'SESSION_EXPIRED' });
185
+ expect(usersRepository.updateUserProfile).not.toHaveBeenCalled();
186
+ });
187
+
188
+ it('requires the current admin role before removing another account’s avatar', async () => {
189
+ tx.user.findUnique.mockResolvedValueOnce({ ...user, id: operator.userId, role: 'USER' });
190
+ await expect(usersService.deleteAvatar(user.id, operator)).rejects.toMatchObject({ statusCode: 403 });
191
+ expect(usersRepository.setAvatarUrl).not.toHaveBeenCalled();
192
+ });
193
+
194
+ it('rejects an admin profile update if the target is absent from the undeleted account lookup', async () => {
195
+ tx.user.findUnique.mockResolvedValueOnce({ ...user, id: operator.userId, role: 'ADMIN' });
196
+ vi.mocked(usersRepository.getUserById).mockResolvedValueOnce(null);
197
+ await expect(usersService.updateProfile(user.id, { firstName: 'Updated' }, operator))
198
+ .rejects.toMatchObject({ statusCode: 404, code: 'USER_NOT_FOUND' });
199
+ expect(usersRepository.updateUserProfile).not.toHaveBeenCalled();
128
200
  });
129
201
  });
@@ -0,0 +1,70 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ import type { Prisma } from '@prisma/client';
3
+ import { startRecurringJob } from '@/jobs/schedule.js';
4
+ import { prisma } from '@libs/prisma.js';
5
+ import { runAccountMutation } from '@libs/account-mutation.js';
6
+ import { logger } from '@libs/logger.js';
7
+ import { avatarFileFromUrl, avatarFileUrl, fileStorageService, type AvatarFile } from '@libs/storage/file-storage.service.js';
8
+ import { lockUser } from '@modules/auth/auth.repo.js';
9
+
10
+ export function avatarCleanupKey(file: AvatarFile): Prisma.AvatarCleanupWhereUniqueInput {
11
+ return { userId_filename: { userId: file.userId, filename: file.filename } };
12
+ }
13
+
14
+ export async function protectPendingAvatar(file: AvatarFile): Promise<void> {
15
+ // This record exists independently of the publish transaction, so an
16
+ // interruption after writing bytes still leaves work for another replica.
17
+ await prisma.avatarCleanup.create({ data: { ...file, dueAt: new Date(Date.now() + 10 * 60_000) } });
18
+ }
19
+
20
+ export async function queueReplacedAvatar(
21
+ tx: Prisma.TransactionClient, userId: string, url: string | null,
22
+ ): Promise<AvatarFile | null> {
23
+ const file = avatarFileFromUrl(userId, url);
24
+ if (!file) {
25
+ if (url) logger.warn({ userId }, 'Avatar URL does not name a local file for this account');
26
+ return null;
27
+ }
28
+ const dueAt = new Date();
29
+ await tx.avatarCleanup.upsert({
30
+ where: avatarCleanupKey(file), create: { ...file, dueAt }, update: { dueAt },
31
+ });
32
+ return file;
33
+ }
34
+
35
+ export async function tryAvatarCleanup(file: AvatarFile | null, immediate = true): Promise<void> {
36
+ if (!file) return;
37
+ try {
38
+ await runAccountMutation(async tx => {
39
+ // Writers and workers take the same owner lock before touching the
40
+ // queue. A locking queue read also protects entries for purged users.
41
+ await lockUser(tx, file.userId);
42
+ const [queued] = await tx.$queryRaw<{ dueAt: Date }[]>`
43
+ SELECT dueAt FROM avatar_cleanup
44
+ WHERE userId = ${file.userId} AND filename = ${file.filename} FOR UPDATE
45
+ `;
46
+ if (!queued || (!immediate && queued.dueAt.getTime() > Date.now())) return;
47
+ const owner = await tx.user.findUnique({ where: { id: file.userId }, select: { avatarUrl: true } });
48
+ if (owner?.avatarUrl !== avatarFileUrl(file)) await fileStorageService.removeAvatarFile(file);
49
+ await tx.avatarCleanup.delete({ where: avatarCleanupKey(file) });
50
+ });
51
+ } catch {
52
+ // A failed unlink keeps its durable entry. Moving its due time forward
53
+ // prevents this file from starving other work in the next bounded batch.
54
+ logger.warn({ userId: file.userId }, 'Avatar cleanup deferred');
55
+ await prisma.avatarCleanup.updateMany({
56
+ where: { userId: file.userId, filename: file.filename }, data: { dueAt: new Date(Date.now() + 60_000) },
57
+ }).catch(() => {});
58
+ }
59
+ }
60
+
61
+ export async function cleanupDueAvatars(): Promise<void> {
62
+ const files = await prisma.avatarCleanup.findMany({
63
+ where: { dueAt: { lte: new Date() } }, orderBy: [{ dueAt: 'asc' }, { userId: 'asc' }, { filename: 'asc' }], take: 50,
64
+ });
65
+ for (const file of files) await tryAvatarCleanup(file, false);
66
+ }
67
+
68
+ export function startAvatarCleanupJob(app: FastifyInstance): void {
69
+ startRecurringJob(app, { name: 'avatar-cleanup', firstRunDelayMs: 60_000, intervalMs: 60_000, run: cleanupDueAvatars });
70
+ }
@@ -6,13 +6,14 @@
6
6
 
7
7
  import type { FastifyRequest, FastifyReply } from 'fastify';
8
8
  import { usersService } from './users.service.js';
9
- import { validateImageFile, validateFileSize } from '@libs/storage/file-validator.js';
9
+ import { validateFileSize } from '@libs/storage/file-validator.js';
10
10
  import { successResponse } from '@shared/responses/successResponse.js';
11
11
  import { clearAuthCookies } from '@libs/cookies.js';
12
12
  import { ChangePasswordSchema, AdminChangePasswordSchema, DeleteAccountSchema } from './users.schemas.js';
13
13
  import type { UpdateProfileInput } from './users.schemas.js';
14
14
  import type { AuthenticatedRequest } from '@shared/types/index.js';
15
15
  import { logger } from '@libs/logger.js';
16
+ import { AppError } from '@shared/errors/AppError.js';
16
17
  import { BadRequestError } from '@shared/errors/errors.js';
17
18
 
18
19
  /**
@@ -32,22 +33,24 @@ class UsersController {
32
33
  * @param reply - Fastify reply
33
34
  */
34
35
  async uploadAvatar(request: AuthenticatedRequest, reply: FastifyReply): Promise<void> {
35
- // Get uploaded file from multipart request
36
- const data = await request.file();
37
-
38
- if (!data) {
39
- throw new BadRequestError('No file uploaded', 'NO_FILE');
36
+ let image: { buffer: Buffer; filename: string; mimetype: string } | undefined;
37
+ // The parser enforces the part, field and one-file caps throughout the form.
38
+ // Save only after it finishes so a limit after the image has the same effect
39
+ // as a limit before it. Only the bounded image buffer reaches the service.
40
+ for await (const part of request.parts()) {
41
+ if (part.type === 'field') {
42
+ if (part.fieldnameTruncated || part.valueTruncated) {
43
+ throw new AppError('MULTIPART_LIMIT', 'A form field exceeds the upload limit', 413);
44
+ }
45
+ continue;
46
+ }
47
+ const buffer = await part.toBuffer();
48
+ validateFileSize(buffer, part.file.truncated);
49
+ image = { buffer, filename: part.filename, mimetype: part.mimetype };
40
50
  }
41
51
 
42
- // A file must be present. Its format is judged from the bytes later
43
- // (imageOptimizerService); the browser-sent type and name are not trusted.
44
- validateImageFile(data);
45
-
46
- // Read file buffer
47
- const buffer = await data.toBuffer();
48
-
49
- // Validate file size, including a file the parser silently cut at the limit
50
- validateFileSize(buffer, data.file.truncated);
52
+ if (request.raw.aborted) throw new BadRequestError('Avatar upload did not finish', 'INVALID_MULTIPART');
53
+ if (!image) throw new BadRequestError('No file uploaded', 'NO_FILE');
51
54
 
52
55
  // Get target user ID (set by resolveMe or resolveTargetUser middleware)
53
56
  const userId = request.targetUserId!;
@@ -55,13 +58,13 @@ class UsersController {
55
58
  logger.info({
56
59
  msg: 'Avatar upload request',
57
60
  userId,
58
- filename: data.filename,
59
- mimetype: data.mimetype,
60
- size: buffer.length,
61
+ filename: image.filename,
62
+ mimetype: image.mimetype,
63
+ size: image.buffer.length,
61
64
  });
62
65
 
63
66
  // Call service to process and save avatar
64
- const { avatarUrl } = await usersService.uploadAvatar(userId, buffer, data.filename);
67
+ const { avatarUrl } = await usersService.uploadAvatar(userId, image.buffer, image.filename, request.user);
65
68
 
66
69
  return reply.send(successResponse('Avatar uploaded successfully', { avatarUrl }));
67
70
  }
@@ -82,7 +85,7 @@ class UsersController {
82
85
  logger.info({ msg: 'Avatar delete request', userId });
83
86
 
84
87
  // Call service to delete avatar
85
- await usersService.deleteAvatar(userId);
88
+ await usersService.deleteAvatar(userId, request.user);
86
89
 
87
90
  return reply.send(successResponse('Avatar deleted successfully', null));
88
91
  }
@@ -105,7 +108,7 @@ class UsersController {
105
108
 
106
109
  logger.info({ msg: 'Update profile request', userId });
107
110
 
108
- const updatedUser = await usersService.updateProfile(userId, body);
111
+ const updatedUser = await usersService.updateProfile(userId, body, request.user);
109
112
 
110
113
  return reply.send(successResponse('Profile updated successfully', updatedUser));
111
114
  }
@@ -129,12 +132,12 @@ class UsersController {
129
132
  if (isAdminAction) {
130
133
  const parsed = AdminChangePasswordSchema.parse(request.body);
131
134
  logger.info({ msg: 'Admin change password request', targetUserId: userId, adminUserId: request.user.userId });
132
- await usersService.changePassword(userId, parsed, true);
135
+ await usersService.changePassword(userId, parsed, request.user);
133
136
  } else {
134
137
  const parsed = ChangePasswordSchema.parse(request.body);
135
138
  logger.info({ msg: 'Change password request', userId });
136
139
  // Keep the device that asked signed in; every other session ends.
137
- await usersService.changePassword(userId, parsed, false, request.user.sessionId);
140
+ await usersService.changePassword(userId, parsed, request.user);
138
141
  }
139
142
 
140
143
  return reply.send(successResponse('Password changed successfully', null));
@@ -158,11 +161,11 @@ class UsersController {
158
161
 
159
162
  if (isAdminAction) {
160
163
  logger.info({ msg: 'Admin delete account request', targetUserId: userId, adminUserId: request.user.userId });
161
- await usersService.deleteAccount(userId, '', true);
164
+ await usersService.deleteAccount(userId, request.user);
162
165
  } else {
163
166
  const parsed = DeleteAccountSchema.parse(request.body);
164
167
  logger.info({ msg: 'Delete account request', userId });
165
- await usersService.deleteAccount(userId, parsed.password, false);
168
+ await usersService.deleteAccount(userId, request.user, parsed.password);
166
169
  }
167
170
 
168
171
  // Only clear cookies if the user is deleting their OWN account
@@ -4,7 +4,7 @@
4
4
  * Data access layer for user operations.
5
5
  */
6
6
 
7
- import { prisma } from '@libs/prisma.js';
7
+ import type { Prisma } from '@prisma/client';
8
8
  import type { UserRole } from '@shared/types/index.js';
9
9
 
10
10
  /**
@@ -45,69 +45,30 @@ class UsersRepository {
45
45
  /**
46
46
  * Gets a user by ID
47
47
  */
48
- async getUserById(userId: string): Promise<SafeUser | null> {
49
- return prisma.user.findUnique({
48
+ async getUserById(userId: string, tx: Prisma.TransactionClient): Promise<SafeUser | null> {
49
+ return tx.user.findUnique({
50
50
  where: { id: userId, deletedAt: null },
51
51
  select: userSelect,
52
52
  });
53
53
  }
54
54
 
55
- /**
56
- * Compare-and-swap of the avatar URL: sets `next` only if the stored URL is
57
- * still `expected` (null matches "no avatar"). Returns whether THIS call made
58
- * the change. One counted UPDATE, so of two parallel uploads exactly one
59
- * replaces any given URL, and only that one deletes the replaced file (see
60
- * usersService.uploadAvatar). Deleted accounts never match.
61
- */
62
- async swapAvatarUrl(userId: string, expected: string | null, next: string): Promise<boolean> {
63
- const { count } = await prisma.user.updateMany({
64
- where: { id: userId, deletedAt: null, avatarUrl: expected },
65
- data: { avatarUrl: next },
66
- });
67
- return count === 1;
68
- }
69
-
70
- /**
71
- * Clears a user's avatar URL
72
- */
73
- async clearUserAvatar(userId: string): Promise<SafeUser> {
74
- return prisma.user.update({
75
- where: { id: userId },
76
- data: { avatarUrl: null },
77
- select: userSelect,
78
- });
55
+ /** Read and write avatar state under the caller's account lock. */
56
+ async setAvatarUrl(tx: Prisma.TransactionClient, userId: string, avatarUrl: string | null): Promise<void> {
57
+ await tx.user.update({ where: { id: userId, deletedAt: null }, data: { avatarUrl } });
79
58
  }
80
59
 
81
- /**
82
- * Updates a user's profile fields
83
- */
84
60
  async updateUserProfile(
85
- userId: string,
86
- data: { firstName?: string; lastName?: string }
61
+ tx: Prisma.TransactionClient, userId: string, data: { firstName?: string; lastName?: string },
87
62
  ): Promise<SafeUser> {
88
- return prisma.user.update({
89
- where: { id: userId },
90
- data,
91
- select: userSelect,
92
- });
93
- }
94
-
95
- /**
96
- * How many OTHER admins could still manage the project: role ADMIN, not
97
- * banned, not deleted. Zero means `userId` is the last one.
98
- */
99
- async countOtherActiveAdmins(userId: string): Promise<number> {
100
- return prisma.user.count({
101
- where: { role: 'ADMIN', isActive: true, deletedAt: null, id: { not: userId } },
102
- });
63
+ return tx.user.update({ where: { id: userId, deletedAt: null }, data, select: userSelect });
103
64
  }
104
65
 
105
66
  /**
106
- * Soft deletes a user: deletedAt set, isActive = false, and the avatar URL
107
- * cleared (its file is removed right after, see usersService.deleteAccount).
67
+ * Soft-deletes the user and detaches the avatar. The caller queues the
68
+ * detached file for cleanup in the same transaction.
108
69
  */
109
- async softDeleteUser(userId: string): Promise<void> {
110
- await prisma.user.update({
70
+ async softDeleteUser(tx: Prisma.TransactionClient, userId: string): Promise<void> {
71
+ await tx.user.update({
111
72
  where: { id: userId },
112
73
  data: {
113
74
  deletedAt: new Date(),