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,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(),
@@ -7,234 +7,122 @@
7
7
  import { usersRepository } from './users.repo.js';
8
8
  import type { SafeUser } from './users.repo.js';
9
9
  import * as authRepo from '@modules/auth/auth.repo.js';
10
- import { sessionRepository } from '@modules/auth/session.repo.js';
11
- import { fileStorageService } from '@libs/storage/file-storage.service.js';
10
+ import { avatarFileUrl, fileStorageService } from '@libs/storage/file-storage.service.js';
11
+ import type { Prisma } from '@prisma/client';
12
+ import { avatarCleanupKey, protectPendingAvatar, queueReplacedAvatar, tryAvatarCleanup } from './avatar-cleanup.js';
12
13
  import { imageOptimizerService } from '@libs/storage/image-optimizer.service.js';
13
14
  import { verifyPassword, hashPassword } from '@libs/password.js';
14
- import { NotFoundError, BadRequestError, ValidationError, ConflictError } from '@shared/errors/errors.js';
15
+ import {
16
+ assertAnotherSignInAdmin, assertMutationActor, revokeAccountCredentials, runAccountMutation,
17
+ type MutationActor,
18
+ } from '@libs/account-mutation.js';
19
+ import { NotFoundError, BadRequestError, ValidationError, ConflictError, ServiceUnavailableError } from '@shared/errors/errors.js';
15
20
  import { logger } from '@libs/logger.js';
16
- import path from 'path';
17
21
  import type { UpdateProfileInput, ChangePasswordInput, AdminChangePasswordInput } from './users.schemas.js';
18
22
 
19
- /**
20
- * How often an upload retries pointing the database at its new file when a
21
- * parallel upload or delete keeps changing the avatar. Each retry means
22
- * someone else won a swap; 5 is plenty for one person's clicks and tabs.
23
- */
24
- const AVATAR_SWAP_ATTEMPTS = 5;
23
+ /** Lock before checking the target so deletion and publishing have a single order. */
24
+ async function lockTarget(tx: Prisma.TransactionClient, userId: string, actor: MutationActor): Promise<SafeUser> {
25
+ await authRepo.lockUser(tx, userId);
26
+ await assertMutationActor(tx, actor, actor.userId === userId ? undefined : 'ADMIN');
27
+ const user = await usersRepository.getUserById(userId, tx);
28
+ if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
29
+ return user;
30
+ }
25
31
 
26
- /**
27
- * Users Service Class
28
- *
29
- * Handles business logic for user profile and avatar operations.
30
- */
31
32
  class UsersService {
32
- /**
33
- * Uploads and sets a user's avatar
34
- *
35
- * Process:
36
- * 1. Optimize the image (bytes decide the format; WebP out, no metadata)
37
- * 2. Write it under a NEW random filename (the old avatar keeps serving)
38
- * 3. Point the database at it with a compare-and-swap, retrying when a
39
- * parallel upload or delete changed the avatar in between
40
- * 4. Delete exactly the file this swap replaced
41
- *
42
- * Why the swap: two uploads at once (double click, two tabs) must end with
43
- * one file on disk, the one the database names. Each replaced URL is replaced
44
- * by exactly one swap, and only that upload deletes its file, so no upload
45
- * can delete a file another upload is about to point the database at.
46
- *
47
- * @param userId - User's unique ID
48
- * @param fileBuffer - Uploaded image buffer
49
- * @param originalFilename - Original filename (for logging)
50
- * @returns The new avatar URL
51
- * @throws NotFoundError if user not found
52
- * @throws ConflictError (AVATAR_BUSY) if the avatar kept changing during the upload
53
- */
54
33
  async uploadAvatar(
55
- userId: string,
56
- fileBuffer: Buffer,
57
- originalFilename: string
34
+ userId: string, fileBuffer: Buffer, _originalFilename: string, actor: MutationActor,
58
35
  ): Promise<{ avatarUrl: string }> {
59
- const user = await usersRepository.getUserById(userId);
60
- if (!user) {
61
- throw new NotFoundError('User not found', 'USER_NOT_FOUND');
62
- }
63
-
64
- logger.info({
65
- msg: 'Processing avatar upload',
66
- userId,
67
- originalFilename,
68
- fileSize: fileBuffer.length,
69
- });
70
-
71
- const optimizedBuffer = await imageOptimizerService.optimizeAvatar(fileBuffer);
72
- const { filename, url } = await fileStorageService.saveAvatar(userId, optimizedBuffer);
73
-
74
- // undefined = not swapped yet; null = swapped and there was no old avatar.
75
- let replaced: string | null | undefined;
36
+ const optimized = await imageOptimizerService.optimizeAvatar(fileBuffer);
37
+ const file = fileStorageService.allocateAvatar(userId);
38
+ const url = avatarFileUrl(file);
39
+ await protectPendingAvatar(file);
40
+
41
+ // If MySQL retries after the rename, reuse this exact immutable file.
42
+ // The durable entry is removed only by the successful commit.
43
+ let published = false;
76
44
  try {
77
- let expected = user.avatarUrl;
78
- for (let attempt = 0; attempt < AVATAR_SWAP_ATTEMPTS && replaced === undefined; attempt++) {
79
- if (await usersRepository.swapAvatarUrl(userId, expected, url)) {
80
- replaced = expected;
81
- break;
45
+ const previous = await runAccountMutation(async tx => {
46
+ const target = await lockTarget(tx, userId, actor);
47
+ const where = avatarCleanupKey(file);
48
+ const pending = await tx.avatarCleanup.findUnique({ where });
49
+ if (!pending || pending.dueAt.getTime() <= Date.now()) {
50
+ throw new ServiceUnavailableError('Avatar upload expired. Please try again.', 'AVATAR_UPLOAD_EXPIRED');
82
51
  }
83
- const current = await usersRepository.getUserById(userId);
84
- if (!current) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
85
- expected = current.avatarUrl;
86
- }
52
+ if (!published) {
53
+ await fileStorageService.publishAvatar(file, optimized);
54
+ published = true;
55
+ }
56
+ await usersRepository.setAvatarUrl(tx, userId, url);
57
+ await tx.avatarCleanup.delete({ where });
58
+ return queueReplacedAvatar(tx, userId, target.avatarUrl);
59
+ });
60
+ await tryAvatarCleanup(previous);
61
+ logger.info({ userId, avatarUrl: url }, 'Avatar uploaded');
62
+ return { avatarUrl: url };
87
63
  } catch (error) {
88
- await fileStorageService.removeAvatarFile(userId, filename);
64
+ await tryAvatarCleanup(file);
89
65
  throw error;
90
66
  }
91
- if (replaced === undefined) {
92
- await fileStorageService.removeAvatarFile(userId, filename);
93
- throw new ConflictError('The avatar changed while uploading. Please try again.', 'AVATAR_BUSY');
94
- }
95
-
96
- if (replaced) {
97
- await fileStorageService.removeAvatarFile(userId, path.basename(replaced));
98
- }
99
-
100
- logger.info({ msg: 'Avatar upload complete', userId, avatarUrl: url });
101
-
102
- return { avatarUrl: url };
103
67
  }
104
68
 
105
- /**
106
- * Deletes a user's avatar
107
- *
108
- * Process:
109
- * 1. Get user from database
110
- * 2. Verify user has an avatar
111
- * 3. Delete avatar directory from file system
112
- * 4. Clear avatar URL in database
113
- *
114
- * @param userId - User's unique ID
115
- * @throws NotFoundError if user not found
116
- * @throws BadRequestError if user has no avatar to delete
117
- */
118
- async deleteAvatar(userId: string): Promise<void> {
119
- // Get current user
120
- const user = await usersRepository.getUserById(userId);
121
- if (!user) {
122
- throw new NotFoundError('User not found', 'USER_NOT_FOUND');
123
- }
124
-
125
- // Check if user has an avatar
126
- if (!user.avatarUrl) {
127
- throw new BadRequestError('User has no avatar to delete', 'NO_AVATAR');
128
- }
129
-
130
- logger.info({ msg: 'Deleting user avatar', userId, avatarUrl: user.avatarUrl });
131
-
132
- // Delete avatar directory and all contents
133
- await fileStorageService.deleteAvatar(userId);
134
-
135
- // Clear avatar URL in database
136
- await usersRepository.clearUserAvatar(userId);
137
-
138
- logger.info({ msg: 'Avatar deleted successfully', userId });
69
+ async deleteAvatar(userId: string, actor: MutationActor): Promise<void> {
70
+ const previous = await runAccountMutation(async tx => {
71
+ const target = await lockTarget(tx, userId, actor);
72
+ if (!target.avatarUrl) throw new BadRequestError('User has no avatar to delete', 'NO_AVATAR');
73
+ await usersRepository.setAvatarUrl(tx, userId, null);
74
+ return queueReplacedAvatar(tx, userId, target.avatarUrl);
75
+ });
76
+ await tryAvatarCleanup(previous);
77
+ logger.info({ userId }, 'Avatar deleted');
139
78
  }
140
79
 
141
- /**
142
- * Updates a user's profile
143
- *
144
- * @param userId - User's unique ID
145
- * @param input - Fields to update (firstName, lastName)
146
- * @returns Updated user
147
- * @throws NotFoundError if user not found
148
- *
149
- * UpdateProfileSchema already guarantees at least one (trimmed, 2-100 char) field.
150
- */
151
- async updateProfile(userId: string, input: UpdateProfileInput): Promise<SafeUser> {
80
+ async updateProfile(userId: string, input: UpdateProfileInput, actor: MutationActor): Promise<SafeUser> {
152
81
  const { firstName, lastName } = input;
153
-
154
- const user = await usersRepository.getUserById(userId);
155
- if (!user) {
156
- throw new NotFoundError('User not found', 'USER_NOT_FOUND');
157
- }
158
-
159
- logger.info({
160
- msg: 'Updating user profile',
161
- userId,
162
- fields: Object.keys(input).filter(k => input[k as keyof UpdateProfileInput] !== undefined),
82
+ const updatedUser = await runAccountMutation(async tx => {
83
+ await lockTarget(tx, userId, actor);
84
+ return usersRepository.updateUserProfile(tx, userId, { firstName, lastName });
163
85
  });
164
-
165
- const updateData: { firstName?: string; lastName?: string } = {};
166
- if (firstName !== undefined) updateData.firstName = firstName;
167
- if (lastName !== undefined) updateData.lastName = lastName;
168
-
169
- const updatedUser = await usersRepository.updateUserProfile(userId, updateData);
170
-
171
- logger.info({ msg: 'User profile updated', userId });
172
-
86
+ logger.info({ userId }, 'User profile updated');
173
87
  return updatedUser;
174
88
  }
175
89
 
176
- /**
177
- * Changes a user's password
178
- *
179
- * Afterwards every OTHER session of the user ends at once. The owner's own
180
- * session (`keepSessionId`, the device that asked) stays signed in: ending it
181
- * too dropped the user on the login page right after "Password changed".
182
- * An admin-forced change (skipPasswordVerification, no keepSessionId) and a
183
- * password reset (auth.service) still end every session.
184
- *
185
- * @param userId - User's unique ID
186
- * @param input - Current and new password
187
- * @param skipPasswordVerification - true for an admin acting on another user
188
- * @param keepSessionId - the owner's current session (request.user.sessionId)
189
- * @throws NotFoundError if user not found
190
- * @throws ValidationError (422 INVALID_CURRENT_PASSWORD) if the current password is wrong
191
- * @throws BadRequestError if new password same as current
192
- */
90
+ /** Change the password and revoke credentials as one database operation. */
193
91
  async changePassword(
194
92
  userId: string,
195
93
  input: ChangePasswordInput | AdminChangePasswordInput,
196
- skipPasswordVerification: boolean = false,
197
- keepSessionId?: string
94
+ actor: MutationActor,
198
95
  ): Promise<void> {
199
96
  const user = await authRepo.findUserById(userId);
200
- if (!user) {
201
- throw new NotFoundError('User not found', 'USER_NOT_FOUND');
202
- }
203
-
204
- if (!skipPasswordVerification) {
205
- const fullInput = input as ChangePasswordInput;
206
- const isValid = await verifyPassword(fullInput.currentPassword, user.password);
207
- // 422, not 401: the caller IS signed in, and a 401 would make the client
208
- // treat it as an expired session and run a pointless token refresh.
209
- if (!isValid) {
210
- throw new ValidationError('Current password is incorrect', 'INVALID_CURRENT_PASSWORD');
211
- }
97
+ if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
98
+
99
+ const selfChange = actor.userId === userId;
100
+ const invalidPassword = (): ValidationError =>
101
+ new ValidationError('Current password is incorrect', 'INVALID_CURRENT_PASSWORD');
102
+ if (selfChange) {
103
+ const { currentPassword } = input as ChangePasswordInput;
104
+ if (!currentPassword || !await verifyPassword(currentPassword, user.password)) throw invalidPassword();
212
105
  }
213
-
214
- const isSamePassword = await verifyPassword(input.newPassword, user.password);
215
- if (isSamePassword) {
106
+ if (await verifyPassword(input.newPassword, user.password)) {
216
107
  throw new BadRequestError('New password must be different from current password', 'SAME_PASSWORD');
217
108
  }
218
109
 
219
110
  const hashedPassword = await hashPassword(input.newPassword);
220
- await authRepo.updateUserPassword(userId, hashedPassword);
221
-
222
- logger.info({ msg: 'User password changed', userId });
223
-
224
- // Security: end every other session and its refresh tokens. Only an owner
225
- // change keeps its own session; without a session id, end them all.
226
- const keep = !skipPasswordVerification && keepSessionId ? keepSessionId : undefined;
227
- if (keep) {
228
- await sessionRepository.deleteOtherUserSessions(userId, keep);
229
- await authRepo.deleteRefreshTokensByUserId(userId, { exceptSessionId: keep });
230
- } else {
231
- await sessionRepository.deleteAllUserSessions(userId);
232
- await authRepo.deleteRefreshTokensByUserId(userId);
233
- }
234
-
235
- logger.info(
236
- { msg: 'Sessions invalidated after password change', userId, keptCurrentSession: Boolean(keep) },
237
- );
111
+ const keep = selfChange ? actor.sessionId : undefined;
112
+ await runAccountMutation(async tx => {
113
+ // Refresh and sign-ins that already checked the old password take this
114
+ // same target lock. Password hashing stays outside the transaction.
115
+ const current = await authRepo.lockUser(tx, userId);
116
+ await assertMutationActor(tx, actor, selfChange ? undefined : 'ADMIN');
117
+ if (!current || current.deletedAt) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
118
+ if (current.password !== user.password) {
119
+ if (selfChange) throw invalidPassword();
120
+ throw new ConflictError('The password has changed. Please try again.', 'PASSWORD_CHANGED');
121
+ }
122
+ await tx.user.update({ where: { id: userId }, data: { password: hashedPassword } });
123
+ await revokeAccountCredentials(tx, userId, keep);
124
+ });
125
+ logger.info({ msg: 'Password changed and sessions invalidated', userId, keptCurrentSession: Boolean(keep) });
238
126
  }
239
127
 
240
128
  /**
@@ -247,52 +135,39 @@ class UsersService {
247
135
  */
248
136
  async deleteAccount(
249
137
  userId: string,
250
- password: string,
251
- skipPasswordVerification: boolean = false
138
+ actor: MutationActor,
139
+ password?: string,
252
140
  ): Promise<void> {
253
- const user = await authRepo.findUserById(userId);
254
- if (!user) {
255
- throw new NotFoundError('User not found', 'USER_NOT_FOUND');
256
- }
257
-
258
- if (!skipPasswordVerification) {
259
- const isValid = await verifyPassword(password, user.password);
141
+ const selfDelete = userId === actor.userId;
142
+ let verifiedHash: string | undefined;
143
+ if (selfDelete) {
144
+ const user = await authRepo.findUserById(userId);
145
+ if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
260
146
  // 422, not 401 (see changePassword): a wrong confirmation is wrong input.
261
- if (!isValid) {
147
+ if (!password || !await verifyPassword(password, user.password)) {
262
148
  throw new ValidationError('Incorrect password', 'INVALID_PASSWORD');
263
149
  }
264
-
265
- // The last active admin deleting their own account would leave nobody
266
- // able to manage the project. Checked after the password, so a wrong
267
- // password still answers INVALID_PASSWORD. (An admin deleting ANOTHER
268
- // admin always leaves themselves, so that path needs no check.)
269
- if (user.role === 'ADMIN' && (await usersRepository.countOtherActiveAdmins(userId)) === 0) {
270
- throw new ConflictError(
271
- 'You are the only admin. Make someone else an admin before deleting your account.',
272
- 'LAST_ADMIN',
273
- );
274
- }
150
+ verifiedHash = user.password;
275
151
  }
276
152
 
277
- logger.info({ msg: 'Soft-deleting user account', userId });
278
-
279
- // Also clears avatarUrl (the photo is removed just below).
280
- await usersRepository.softDeleteUser(userId);
281
-
282
- // Delete all sessions and refresh tokens
283
- await sessionRepository.deleteAllUserSessions(userId);
284
- await authRepo.deleteRefreshTokensByUserId(userId);
153
+ const previous = await runAccountMutation(async tx => {
154
+ await assertMutationActor(tx, actor, selfDelete ? undefined : 'ADMIN');
155
+ const user = await tx.user.findUnique({ where: { id: userId, deletedAt: null } });
156
+ if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
157
+ // Password verification is expensive. Confirm the hash has not changed
158
+ // under the transaction before acting on the result.
159
+ if (selfDelete && user.password !== verifiedHash) {
160
+ throw new ValidationError('Incorrect password', 'INVALID_PASSWORD');
161
+ }
162
+ await assertAnotherSignInAdmin(tx, user);
163
+ await usersRepository.softDeleteUser(tx, userId);
164
+ await revokeAccountCredentials(tx, userId);
165
+ return queueReplacedAvatar(tx, userId, user.avatarUrl);
166
+ });
285
167
 
286
- // The avatar is PUBLIC (/uploads): remove it now, not at the 30-day purge,
287
- // so a deleted account's photo stops being reachable at once. A failure
288
- // must not undo the deletion: log it, the purge (files first) retries.
289
- // Private files stay until the purge, unreachable since the owner can no
290
- // longer sign in.
291
- try {
292
- await fileStorageService.deleteAvatar(userId);
293
- } catch (error) {
294
- logger.error({ err: error, msg: 'Account deleted but its public avatar could not be removed', userId });
295
- }
168
+ // Only the detached avatar is eligible for removal. A concurrent restore
169
+ // and upload can publish a new file before this cleanup acquires the lock.
170
+ await tryAvatarCleanup(previous);
296
171
 
297
172
  logger.info({ msg: 'User account deleted', userId });
298
173
  }
@@ -1,3 +1,5 @@
1
+ import { MAX_PAGE } from '@shared/schemas/pagination.schema.js';
2
+
1
3
  export function paginatedResponse<T>(
2
4
  message: string,
3
5
  items: T[],
@@ -19,7 +21,8 @@ export function paginatedResponse<T>(
19
21
  };
20
22
  };
21
23
  } {
22
- const totalPages = Math.ceil(totalItems / limit);
24
+ // Report only the pages the API accepts. totalItems still counts every match.
25
+ const totalPages = Math.min(MAX_PAGE, Math.ceil(totalItems / limit));
23
26
  return {
24
27
  success: true as const,
25
28
  message,
@@ -1,7 +1,11 @@
1
1
  import { z } from 'zod';
2
2
 
3
+ // Offset lists are for browsing. A page ceiling bounds how far the database
4
+ // can be asked to walk before returning a page, even when limit is also large.
5
+ export const MAX_PAGE = 1000;
6
+
3
7
  export const PaginationSchema = z.object({
4
- page: z.coerce.number().int().min(1).default(1),
8
+ page: z.coerce.number().int().min(1).max(MAX_PAGE).default(1),
5
9
  limit: z.coerce.number().int().min(1).max(100).default(10),
6
10
  });
7
11