create-tigra 3.3.0 → 4.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 (203) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +72 -10
  4. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  5. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  6. package/modules/email-verification/server/verification.controller.ts +3 -1
  7. package/modules/email-verification/server/verification.service.ts +44 -13
  8. package/package.json +3 -2
  9. package/template/.github/dependabot.yml +47 -0
  10. package/template/.github/workflows/audit.yml +36 -0
  11. package/template/.github/workflows/ci.yml +79 -0
  12. package/template/AGENTS.md +18 -9
  13. package/template/client/.dockerignore +1 -0
  14. package/template/client/.env.example.production +13 -2
  15. package/template/client/AGENTS.md +13 -5
  16. package/template/client/Dockerfile +186 -14
  17. package/template/client/next.config.ts +1 -1
  18. package/template/client/package-lock.json +15983 -14181
  19. package/template/client/package.json +56 -48
  20. package/template/client/scripts/check-sharp.mjs +53 -0
  21. package/template/client/scripts/next-dev.cjs +5 -1
  22. package/template/client/src/__tests__/proxy.test.ts +92 -0
  23. package/template/client/src/app/healthz/route.ts +16 -0
  24. package/template/client/src/app/layout.tsx +9 -3
  25. package/template/client/src/app/page.tsx +2 -2
  26. package/template/client/src/app/providers.tsx +23 -4
  27. package/template/client/src/components/layout/Header.tsx +7 -3
  28. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  29. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  30. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  31. package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
  32. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  33. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  34. package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  37. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  38. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  39. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  40. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  41. package/template/client/src/lib/api/api.types.ts +14 -0
  42. package/template/client/src/lib/api/axios.config.ts +101 -15
  43. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  44. package/template/client/src/lib/api/session-events.ts +29 -0
  45. package/template/client/src/lib/constants/routes.ts +12 -0
  46. package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
  47. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  48. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  49. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  50. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  51. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  52. package/template/client/src/lib/utils/error.ts +81 -0
  53. package/template/client/src/lib/utils/form.ts +31 -0
  54. package/template/client/src/lib/utils/paths.ts +18 -0
  55. package/template/client/src/lib/utils/session-marker.ts +24 -0
  56. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  57. package/template/client/src/store/__tests__/store.test.ts +44 -0
  58. package/template/client/src/store/index.ts +26 -8
  59. package/template/client/vitest.config.mts +48 -0
  60. package/template/server/.env.example +280 -270
  61. package/template/server/.env.example.production +283 -242
  62. package/template/server/AGENTS.md +13 -4
  63. package/template/server/Dockerfile +176 -14
  64. package/template/server/docker-compose.yml +4 -2
  65. package/template/server/docs/deployment.md +63 -0
  66. package/template/server/docs/logging.md +52 -4
  67. package/template/server/docs/rate-limits.md +153 -0
  68. package/template/server/docs/testing.md +63 -0
  69. package/template/server/eslint.config.mjs +19 -0
  70. package/template/server/package-lock.json +8784 -8743
  71. package/template/server/package.json +79 -75
  72. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  73. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  74. package/template/server/prisma/schema.prisma +0 -3
  75. package/template/server/scripts/check-heic.mjs +40 -0
  76. package/template/server/scripts/check-sharp.mjs +53 -0
  77. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  78. package/template/server/src/app.ts +248 -346
  79. package/template/server/src/config/__tests__/env.test.ts +219 -0
  80. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  81. package/template/server/src/config/env.ts +326 -182
  82. package/template/server/src/config/rate-limit.config.ts +157 -106
  83. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  84. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  85. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  86. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  87. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  88. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  89. package/template/server/src/jobs/index.ts +12 -2
  90. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  91. package/template/server/src/jobs/schedule.ts +50 -0
  92. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  93. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  94. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  95. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  96. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  97. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  98. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  99. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  100. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  101. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  102. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  103. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  104. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  105. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  106. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  107. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  108. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  109. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  110. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  111. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  112. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  113. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  114. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  115. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  116. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  117. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  118. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  119. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  120. package/template/server/src/libs/auth.ts +39 -10
  121. package/template/server/src/libs/client-ip.ts +158 -77
  122. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  123. package/template/server/src/libs/cookies.ts +53 -14
  124. package/template/server/src/libs/email-quota.ts +74 -0
  125. package/template/server/src/libs/email.ts +46 -9
  126. package/template/server/src/libs/error-handler.ts +111 -0
  127. package/template/server/src/libs/health-routes.ts +53 -0
  128. package/template/server/src/libs/http.ts +139 -47
  129. package/template/server/src/libs/ip-address.ts +37 -0
  130. package/template/server/src/libs/ip-block.ts +284 -221
  131. package/template/server/src/libs/logger.ts +41 -12
  132. package/template/server/src/libs/monitoring.ts +127 -41
  133. package/template/server/src/libs/observability/sentry.ts +1 -1
  134. package/template/server/src/libs/origin-check.ts +9 -7
  135. package/template/server/src/libs/prisma.ts +47 -4
  136. package/template/server/src/libs/query-counter.ts +71 -59
  137. package/template/server/src/libs/rate-limiting.ts +110 -0
  138. package/template/server/src/libs/redis-required.ts +28 -0
  139. package/template/server/src/libs/redis.ts +27 -1
  140. package/template/server/src/libs/request-id.ts +18 -0
  141. package/template/server/src/libs/requestLogger.ts +112 -17
  142. package/template/server/src/libs/safe-http.ts +101 -0
  143. package/template/server/src/libs/shutdown.ts +87 -0
  144. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  145. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  146. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  147. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  148. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  149. package/template/server/src/libs/storage/file-validator.ts +48 -46
  150. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  151. package/template/server/src/libs/token-hash.ts +18 -0
  152. package/template/server/src/libs/url-safety.ts +127 -121
  153. package/template/server/src/libs/validation-errors.ts +86 -0
  154. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  155. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  156. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  157. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  158. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  159. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  160. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  161. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  162. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  163. package/template/server/src/modules/admin/admin.service.ts +66 -4
  164. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  165. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  166. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  167. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  168. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  170. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  171. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  172. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  173. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  174. package/template/server/src/modules/auth/auth.service.ts +167 -96
  175. package/template/server/src/modules/auth/session.repo.ts +12 -0
  176. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  177. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  178. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  179. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  180. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  181. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  182. package/template/server/src/modules/users/users.controller.ts +9 -38
  183. package/template/server/src/modules/users/users.repo.ts +23 -7
  184. package/template/server/src/modules/users/users.routes.ts +3 -22
  185. package/template/server/src/modules/users/users.schemas.ts +15 -9
  186. package/template/server/src/modules/users/users.service.ts +105 -93
  187. package/template/server/src/scripts/make-admin.ts +48 -0
  188. package/template/server/src/server.ts +48 -26
  189. package/template/server/src/shared/errors/AppError.ts +27 -1
  190. package/template/server/src/shared/errors/errors.ts +42 -5
  191. package/template/server/src/shared/responses/successResponse.ts +22 -3
  192. package/template/server/src/shared/types/index.ts +7 -0
  193. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  194. package/template/server/src/test/integration-helpers.ts +343 -0
  195. package/template/server/src/test/integration-services.ts +74 -0
  196. package/template/server/src/test/integration.global-setup.ts +144 -0
  197. package/template/server/src/test/integration.setup.ts +35 -158
  198. package/template/server/src/test/setup.ts +3 -10
  199. package/template/server/tsconfig.build.json +1 -1
  200. package/template/server/tsconfig.json +1 -0
  201. package/template/server/vitest.config.ts +17 -4
  202. package/template/server/vitest.integration.config.ts +18 -13
  203. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -15,18 +15,25 @@ export const UserIdParamSchema = z.object({
15
15
  userId: z.string().uuid({ message: 'Invalid user ID format' }),
16
16
  });
17
17
 
18
- /** Alias for backward compatibility */
19
- export const GetUserAvatarSchema = UserIdParamSchema;
20
-
21
18
  /**
22
19
  * Schema for updating user profile
23
20
  *
24
- * All fields optional — at least one must be provided (validated in service layer)
21
+ * Both fields optional, but at least one must be sent. That rule lives here,
22
+ * not in the service, so an empty update is wrong input like any other:
23
+ * 422 VALIDATION_FAILED naming both fields. trim() runs FIRST (Zod 4 runs the
24
+ * steps in order; a length check before it let " " become an empty name).
25
25
  */
26
- export const UpdateProfileSchema = z.object({
27
- firstName: z.string().min(2, 'First name must be at least 2 characters').max(100).trim().optional(),
28
- lastName: z.string().min(2, 'Last name must be at least 2 characters').max(100).trim().optional(),
29
- });
26
+ export const UpdateProfileSchema = z
27
+ .object({
28
+ firstName: z.string().trim().min(2, 'First name must be at least 2 characters').max(100).optional(),
29
+ lastName: z.string().trim().min(2, 'Last name must be at least 2 characters').max(100).optional(),
30
+ })
31
+ .superRefine((input, ctx) => {
32
+ if (input.firstName !== undefined || input.lastName !== undefined) return;
33
+ for (const field of ['firstName', 'lastName'] as const) {
34
+ ctx.addIssue({ code: 'custom', path: [field], message: 'Send a first name or a last name' });
35
+ }
36
+ });
30
37
 
31
38
  /**
32
39
  * Schema for changing user password
@@ -72,7 +79,6 @@ export const AdminChangePasswordSchema = z.object({
72
79
  * Type inference from schemas
73
80
  */
74
81
  export type UserIdParams = z.infer<typeof UserIdParamSchema>;
75
- export type GetUserAvatarParams = UserIdParams;
76
82
  export type UpdateProfileInput = z.infer<typeof UpdateProfileSchema>;
77
83
  export type ChangePasswordInput = z.infer<typeof ChangePasswordSchema>;
78
84
  export type AdminChangePasswordInput = z.infer<typeof AdminChangePasswordSchema>;
@@ -11,11 +11,18 @@ import { sessionRepository } from '@modules/auth/session.repo.js';
11
11
  import { fileStorageService } from '@libs/storage/file-storage.service.js';
12
12
  import { imageOptimizerService } from '@libs/storage/image-optimizer.service.js';
13
13
  import { verifyPassword, hashPassword } from '@libs/password.js';
14
- import { NotFoundError, BadRequestError, UnauthorizedError } from '@shared/errors/errors.js';
14
+ import { NotFoundError, BadRequestError, ValidationError, ConflictError } from '@shared/errors/errors.js';
15
15
  import { logger } from '@libs/logger.js';
16
16
  import path from 'path';
17
17
  import type { UpdateProfileInput, ChangePasswordInput, AdminChangePasswordInput } from './users.schemas.js';
18
18
 
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;
25
+
19
26
  /**
20
27
  * Users Service Class
21
28
  *
@@ -26,24 +33,29 @@ class UsersService {
26
33
  * Uploads and sets a user's avatar
27
34
  *
28
35
  * Process:
29
- * 1. Get user from database (need first/last name for SEO filename)
30
- * 2. Optimize image (resize, compress, convert to WebP)
31
- * 3. Generate SEO-friendly filename
32
- * 4. Save to user-specific directory
33
- * 5. Update user record with avatar URL
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.
34
46
  *
35
47
  * @param userId - User's unique ID
36
48
  * @param fileBuffer - Uploaded image buffer
37
49
  * @param originalFilename - Original filename (for logging)
38
- * @returns Updated user with new avatar URL
50
+ * @returns The new avatar URL
39
51
  * @throws NotFoundError if user not found
52
+ * @throws ConflictError (AVATAR_BUSY) if the avatar kept changing during the upload
40
53
  */
41
54
  async uploadAvatar(
42
55
  userId: string,
43
56
  fileBuffer: Buffer,
44
57
  originalFilename: string
45
- ): Promise<SafeUser> {
46
- // Get current user
58
+ ): Promise<{ avatarUrl: string }> {
47
59
  const user = await usersRepository.getUserById(userId);
48
60
  if (!user) {
49
61
  throw new NotFoundError('User not found', 'USER_NOT_FOUND');
@@ -56,30 +68,38 @@ class UsersService {
56
68
  fileSize: fileBuffer.length,
57
69
  });
58
70
 
59
- // Optimize image (resize, compress, convert to WebP)
60
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;
76
+ 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;
82
+ }
83
+ const current = await usersRepository.getUserById(userId);
84
+ if (!current) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
85
+ expected = current.avatarUrl;
86
+ }
87
+ } catch (error) {
88
+ await fileStorageService.removeAvatarFile(userId, filename);
89
+ throw error;
90
+ }
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
+ }
61
95
 
62
- // Save to user-specific directory with SEO-friendly filename
63
- const { filename, url } = await fileStorageService.saveAvatar(
64
- userId,
65
- optimizedBuffer,
66
- user.firstName,
67
- user.lastName
68
- );
69
-
70
- logger.info({
71
- msg: 'Avatar file saved',
72
- userId,
73
- filename,
74
- url,
75
- });
76
-
77
- // Update user record with avatar URL
78
- const updatedUser = await usersRepository.updateUserAvatar(userId, url);
96
+ if (replaced) {
97
+ await fileStorageService.removeAvatarFile(userId, path.basename(replaced));
98
+ }
79
99
 
80
100
  logger.info({ msg: 'Avatar upload complete', userId, avatarUrl: url });
81
101
 
82
- return updatedUser;
102
+ return { avatarUrl: url };
83
103
  }
84
104
 
85
105
  /**
@@ -118,56 +138,6 @@ class UsersService {
118
138
  logger.info({ msg: 'Avatar deleted successfully', userId });
119
139
  }
120
140
 
121
- /**
122
- * Gets a user's avatar file path
123
- *
124
- * Process:
125
- * 1. Get user from database
126
- * 2. Verify user has an avatar
127
- * 3. Extract filename from avatar URL
128
- * 4. Build and verify file path
129
- *
130
- * @param userId - User's unique ID
131
- * @returns Absolute file path and public URL
132
- * @throws NotFoundError if user not found or has no avatar
133
- */
134
- async getAvatar(userId: string): Promise<{ path: string; url: string }> {
135
- // Get user
136
- const user = await usersRepository.getUserById(userId);
137
- if (!user) {
138
- throw new NotFoundError('User not found', 'USER_NOT_FOUND');
139
- }
140
-
141
- // Check if user has an avatar
142
- if (!user.avatarUrl) {
143
- throw new NotFoundError('User has no avatar', 'NO_AVATAR');
144
- }
145
-
146
- // Extract filename from URL (last segment)
147
- // URL format: /uploads/users/{userId}/avatar/{filename}
148
- const filename = path.basename(user.avatarUrl);
149
-
150
- // Build full file path
151
- const filePath = fileStorageService.getAvatarPath(userId, filename);
152
-
153
- // Verify file exists on disk
154
- const exists = await fileStorageService.fileExists(filePath);
155
- if (!exists) {
156
- logger.error({
157
- msg: 'Avatar file missing from disk',
158
- userId,
159
- avatarUrl: user.avatarUrl,
160
- filePath,
161
- });
162
- throw new NotFoundError('Avatar file not found on disk', 'AVATAR_FILE_NOT_FOUND');
163
- }
164
-
165
- return {
166
- path: filePath,
167
- url: user.avatarUrl,
168
- };
169
- }
170
-
171
141
  /**
172
142
  * Updates a user's profile
173
143
  *
@@ -175,13 +145,11 @@ class UsersService {
175
145
  * @param input - Fields to update (firstName, lastName)
176
146
  * @returns Updated user
177
147
  * @throws NotFoundError if user not found
178
- * @throws BadRequestError if no fields provided
148
+ *
149
+ * UpdateProfileSchema already guarantees at least one (trimmed, 2-100 char) field.
179
150
  */
180
151
  async updateProfile(userId: string, input: UpdateProfileInput): Promise<SafeUser> {
181
152
  const { firstName, lastName } = input;
182
- if (!firstName && !lastName) {
183
- throw new BadRequestError('At least one field must be provided', 'INVALID_INPUT');
184
- }
185
153
 
186
154
  const user = await usersRepository.getUserById(userId);
187
155
  if (!user) {
@@ -195,8 +163,8 @@ class UsersService {
195
163
  });
196
164
 
197
165
  const updateData: { firstName?: string; lastName?: string } = {};
198
- if (firstName) updateData.firstName = firstName;
199
- if (lastName) updateData.lastName = lastName;
166
+ if (firstName !== undefined) updateData.firstName = firstName;
167
+ if (lastName !== undefined) updateData.lastName = lastName;
200
168
 
201
169
  const updatedUser = await usersRepository.updateUserProfile(userId, updateData);
202
170
 
@@ -208,16 +176,25 @@ class UsersService {
208
176
  /**
209
177
  * Changes a user's password
210
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
+ *
211
185
  * @param userId - User's unique ID
212
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)
213
189
  * @throws NotFoundError if user not found
214
- * @throws UnauthorizedError if current password is wrong
190
+ * @throws ValidationError (422 INVALID_CURRENT_PASSWORD) if the current password is wrong
215
191
  * @throws BadRequestError if new password same as current
216
192
  */
217
193
  async changePassword(
218
194
  userId: string,
219
195
  input: ChangePasswordInput | AdminChangePasswordInput,
220
- skipPasswordVerification: boolean = false
196
+ skipPasswordVerification: boolean = false,
197
+ keepSessionId?: string
221
198
  ): Promise<void> {
222
199
  const user = await authRepo.findUserById(userId);
223
200
  if (!user) {
@@ -227,8 +204,10 @@ class UsersService {
227
204
  if (!skipPasswordVerification) {
228
205
  const fullInput = input as ChangePasswordInput;
229
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.
230
209
  if (!isValid) {
231
- throw new UnauthorizedError('Current password is incorrect', 'INVALID_CREDENTIALS');
210
+ throw new ValidationError('Current password is incorrect', 'INVALID_CURRENT_PASSWORD');
232
211
  }
233
212
  }
234
213
 
@@ -242,11 +221,20 @@ class UsersService {
242
221
 
243
222
  logger.info({ msg: 'User password changed', userId });
244
223
 
245
- // Security: invalidate all sessions and refresh tokens
246
- await sessionRepository.deleteAllUserSessions(userId);
247
- await authRepo.deleteRefreshTokensByUserId(userId);
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
+ }
248
234
 
249
- logger.info({ msg: 'All sessions invalidated after password change', userId });
235
+ logger.info(
236
+ { msg: 'Sessions invalidated after password change', userId, keptCurrentSession: Boolean(keep) },
237
+ );
250
238
  }
251
239
 
252
240
  /**
@@ -255,7 +243,7 @@ class UsersService {
255
243
  * @param userId - User's unique ID
256
244
  * @param password - Password confirmation
257
245
  * @throws NotFoundError if user not found
258
- * @throws UnauthorizedError if password is wrong
246
+ * @throws ValidationError (422 INVALID_PASSWORD) if the password is wrong
259
247
  */
260
248
  async deleteAccount(
261
249
  userId: string,
@@ -269,19 +257,43 @@ class UsersService {
269
257
 
270
258
  if (!skipPasswordVerification) {
271
259
  const isValid = await verifyPassword(password, user.password);
260
+ // 422, not 401 (see changePassword): a wrong confirmation is wrong input.
272
261
  if (!isValid) {
273
- throw new UnauthorizedError('Incorrect password', 'INVALID_CREDENTIALS');
262
+ throw new ValidationError('Incorrect password', 'INVALID_PASSWORD');
263
+ }
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
274
  }
275
275
  }
276
276
 
277
277
  logger.info({ msg: 'Soft-deleting user account', userId });
278
278
 
279
+ // Also clears avatarUrl (the photo is removed just below).
279
280
  await usersRepository.softDeleteUser(userId);
280
281
 
281
282
  // Delete all sessions and refresh tokens
282
283
  await sessionRepository.deleteAllUserSessions(userId);
283
284
  await authRepo.deleteRefreshTokensByUserId(userId);
284
285
 
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
+ }
296
+
285
297
  logger.info({ msg: 'User account deleted', userId });
286
298
  }
287
299
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * make-admin: promote an existing account to ADMIN.
3
+ *
4
+ * Production (Coolify: the server app's Terminal): node dist/scripts/make-admin.js you@example.com
5
+ * Local development: npm run make-admin -- you@example.com
6
+ *
7
+ * The person signs up in the app first, with their own password; this only
8
+ * changes that account's role (and marks its email verified). No password is
9
+ * asked for, stored or printed, and nothing else is printed but the email and
10
+ * the result, never DATABASE_URL. Uses the same env as the server (the
11
+ * container's variables, or server/.env locally).
12
+ * Exit code 0: promoted or already an admin. 1: anything else.
13
+ */
14
+ import { prisma } from '@libs/prisma.js';
15
+ import { adminService } from '@modules/admin/admin.service.js';
16
+
17
+ const MESSAGES = {
18
+ promoted: (email: string) => `${email} is now an admin.`,
19
+ 'already-admin': (email: string) => `${email} is already an admin.`,
20
+ 'not-found': () => 'No account with that email. Sign up in the app first, then run this again.',
21
+ deleted: () => 'That account is deleted. Restore it first.',
22
+ banned: () => 'That account is banned. Unban it first.',
23
+ } as const;
24
+
25
+ async function main(): Promise<number> {
26
+ const email = process.argv[2];
27
+ if (!email || !email.includes('@')) {
28
+ console.error('Usage: node dist/scripts/make-admin.js <email> (local: npm run make-admin -- <email>)');
29
+ return 1;
30
+ }
31
+ const outcome = await adminService.promoteToAdmin(email);
32
+ const message = MESSAGES[outcome](email.trim().toLowerCase());
33
+ const ok = outcome === 'promoted' || outcome === 'already-admin';
34
+ (ok ? console.log : console.error)(message);
35
+ return ok ? 0 : 1;
36
+ }
37
+
38
+ main()
39
+ .then(async (code) => {
40
+ await prisma.$disconnect();
41
+ process.exit(code);
42
+ })
43
+ .catch(async (error: unknown) => {
44
+ // The message only (a Prisma connection error can carry the database host).
45
+ console.error(`make-admin failed: ${error instanceof Error ? error.message.split('\n')[0] : 'unknown error'}`);
46
+ await prisma.$disconnect().catch(() => undefined);
47
+ process.exit(1);
48
+ });
@@ -7,58 +7,80 @@ initSentry();
7
7
  import { env } from '@config/env.js';
8
8
  import { logger } from '@libs/logger.js';
9
9
  import { testDatabaseConnection, disconnectPrisma } from '@libs/prisma.js';
10
- import { connectRedis, disconnectRedis } from '@libs/redis.js';
10
+ import { connectRedis, disconnectRedis, waitForRedisReady } from '@libs/redis.js';
11
+ import { createShutdown } from '@libs/shutdown.js';
11
12
  import { buildApp } from './app.js';
12
13
 
14
+ /** How long a production start waits for Redis before refusing (see start()). */
15
+ const REDIS_BOOT_WAIT_MS = 10_000;
16
+
13
17
  async function start(): Promise<void> {
14
18
  let app: Awaited<ReturnType<typeof buildApp>> | null = null;
15
- let isShuttingDown = false;
16
-
17
- // Graceful shutdown
18
- const shutdown = async (signal: string): Promise<void> => {
19
- if (isShuttingDown) return; // Prevent multiple shutdown attempts
20
- isShuttingDown = true;
21
19
 
22
- logger.info(`[SERVER] Received ${signal} - shutting down gracefully`);
23
- try {
20
+ // One shutdown for every way the process ends: exit 0 after a signal, 1 after
21
+ // a crash or a failed start, 1 if closing takes longer than 8 s (see libs/shutdown.ts).
22
+ const shutdown = createShutdown({
23
+ close: async () => {
24
24
  if (app) {
25
25
  await app.close();
26
26
  }
27
27
  await disconnectRedis();
28
28
  await disconnectPrisma();
29
- logger.info('[SERVER] Shutdown complete');
30
- process.exit(0);
31
- } catch (error) {
32
- logger.error(error, '[SERVER] Error during shutdown');
33
- process.exit(1);
34
- }
35
- };
29
+ },
30
+ exit: (code) => process.exit(code),
31
+ logger,
32
+ });
36
33
 
37
34
  // Register signal handlers early
38
- process.on('SIGINT', () => shutdown('SIGINT'));
39
- process.on('SIGTERM', () => shutdown('SIGTERM'));
35
+ process.on('SIGINT', () => void shutdown('SIGINT'));
36
+ process.on('SIGTERM', () => void shutdown('SIGTERM'));
40
37
  process.on('uncaughtException', (error) => {
41
- logger.fatal(error, '[SERVER] Uncaught exception');
42
- shutdown('uncaughtException');
38
+ logger.fatal({ err: error }, '[SERVER] Uncaught exception');
39
+ void shutdown('uncaughtException');
43
40
  });
44
41
  process.on('unhandledRejection', (reason) => {
45
- logger.fatal(reason, '[SERVER] Unhandled rejection');
46
- shutdown('unhandledRejection');
42
+ // { err } even for a non-Error reason: pino would read a bare string as the message.
43
+ logger.fatal({ err: reason }, '[SERVER] Unhandled rejection');
44
+ void shutdown('unhandledRejection');
47
45
  });
48
46
 
49
47
  try {
50
- // Test external connections (non-fatal)
48
+ // The database check is only logged here: the Docker CMD already ran
49
+ // `prisma migrate deploy`, which fails the start when the database cannot
50
+ // be reached.
51
51
  await testDatabaseConnection();
52
- await connectRedis();
52
+
53
+ // Redis at boot. In production an unreachable Redis stops the start (exit
54
+ // 1): it is almost always a wrong REDIS_URL, and the app would otherwise
55
+ // run with rate limits, login lockout and IP blocks silently off. On
56
+ // Coolify the failed container never becomes healthy, so a rolling deploy
57
+ // keeps the old one serving. It may be just starting too (a server
58
+ // reboot), hence the wait. After boot, outages stay non-fatal
59
+ // (libs/redis.ts). Outside production the server starts without it.
60
+ const redisReady = await connectRedis();
61
+ if (env.NODE_ENV === 'production' && !redisReady) {
62
+ logger.info(`[SERVER] Waiting up to ${REDIS_BOOT_WAIT_MS / 1000}s for Redis`);
63
+ if (!(await waitForRedisReady(REDIS_BOOT_WAIT_MS))) {
64
+ // Never the URL: it carries the password.
65
+ logger.fatal(
66
+ '[SERVER] Redis is not reachable at boot: production refuses to start without it ' +
67
+ '(rate limits, login lockout and IP blocks would be off). Check REDIS_URL.',
68
+ );
69
+ await shutdown('startup-error');
70
+ return;
71
+ }
72
+ }
53
73
 
54
74
  app = await buildApp();
55
75
 
56
76
  await app.listen({ port: env.PORT, host: env.HOST });
57
77
  logger.info(`[SERVER] Started on http://${env.HOST}:${env.PORT} [${env.NODE_ENV}]`);
58
78
  } catch (error) {
59
- logger.fatal(error, '[SERVER] Failed to start');
79
+ logger.fatal({ err: error }, '[SERVER] Failed to start');
60
80
  await shutdown('startup-error');
61
81
  }
62
82
  }
63
83
 
64
- start();
84
+ // start() handles its own failures (it logs them and exits 1 through shutdown),
85
+ // so nothing waits on its promise.
86
+ void start();
@@ -1,12 +1,38 @@
1
+ /**
2
+ * One wrong input field in a 422 VALIDATION_FAILED answer: where it is and
3
+ * why it was refused. Never the submitted value (see libs/validation-errors.ts).
4
+ */
5
+ export interface FieldError {
6
+ /** Path inside the request part, dot-joined ("email", "address.city"), or the part itself ("body"). */
7
+ field: string;
8
+ message: string;
9
+ }
10
+
1
11
  export class AppError extends Error {
2
12
  public readonly isAppError = true;
3
13
  public readonly code: string;
4
14
  public readonly statusCode: number;
15
+ /**
16
+ * Whole seconds until the caller may try again (rate limits, login lock, IP
17
+ * auto-block). Sent in the JSON body because the client runs on another
18
+ * origin and CORS does not expose the Retry-After header to it.
19
+ */
20
+ public readonly retryAfterSeconds?: number;
21
+ /** The wrong fields, for validation failures only (sent as `error.fields`). */
22
+ public readonly fields?: FieldError[];
5
23
 
6
- constructor(code: string, message: string, statusCode: number) {
24
+ constructor(
25
+ code: string,
26
+ message: string,
27
+ statusCode: number,
28
+ retryAfterSeconds?: number,
29
+ fields?: FieldError[],
30
+ ) {
7
31
  super(message);
8
32
  this.code = code;
9
33
  this.statusCode = statusCode;
34
+ this.retryAfterSeconds = retryAfterSeconds;
35
+ this.fields = fields;
10
36
  this.name = this.constructor.name;
11
37
  Error.captureStackTrace(this, this.constructor);
12
38
  }
@@ -1,4 +1,4 @@
1
- import { AppError } from './AppError.js';
1
+ import { AppError, type FieldError } from './AppError.js';
2
2
 
3
3
  export class BadRequestError extends AppError {
4
4
  constructor(message = 'Bad request', code = 'BAD_REQUEST') {
@@ -6,9 +6,14 @@ export class BadRequestError extends AppError {
6
6
  }
7
7
  }
8
8
 
9
+ /**
10
+ * 422. With `fields` it is the one shape for wrong input (VALIDATION_FAILED,
11
+ * built by libs/validation-errors.ts); without, a specific check such as an
12
+ * upload's FILE_* or IMAGE_* code.
13
+ */
9
14
  export class ValidationError extends AppError {
10
- constructor(message = 'Validation failed', code = 'VALIDATION_FAILED') {
11
- super(code, message, 422);
15
+ constructor(message = 'Validation failed', code = 'VALIDATION_FAILED', fields?: FieldError[]) {
16
+ super(code, message, 422, undefined, fields);
12
17
  }
13
18
  }
14
19
 
@@ -19,11 +24,33 @@ export class UnauthorizedError extends AppError {
19
24
  }
20
25
 
21
26
  export class ForbiddenError extends AppError {
22
- constructor(message = 'Forbidden', code = 'FORBIDDEN') {
23
- super(code, message, 403);
27
+ constructor(message = 'Forbidden', code = 'FORBIDDEN', retryAfterSeconds?: number) {
28
+ super(code, message, 403, retryAfterSeconds);
24
29
  }
25
30
  }
26
31
 
32
+ /**
33
+ * 429 with the wait time. Codes in use: RATE_LIMIT_EXCEEDED (a route limit),
34
+ * LOGIN_LOCKED (too many failed sign-ins for this email + IP) and
35
+ * EMAIL_RATE_LIMITED (too many emails to one address). See docs/rate-limits.md.
36
+ */
37
+ export class TooManyRequestsError extends AppError {
38
+ constructor(message: string, code: string, retryAfterSeconds: number) {
39
+ super(code, message, 429, Math.max(1, Math.ceil(retryAfterSeconds)));
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Human wait time for user-facing messages: "45 seconds", "1 minute", "15 minutes".
45
+ * Minutes round up, so the user is never told to retry too early.
46
+ */
47
+ export function describeWait(seconds: number): string {
48
+ const s = Math.max(1, Math.ceil(seconds));
49
+ if (s < 60) return `${s} ${s === 1 ? 'second' : 'seconds'}`;
50
+ const m = Math.ceil(s / 60);
51
+ return `${m} ${m === 1 ? 'minute' : 'minutes'}`;
52
+ }
53
+
27
54
  export class NotFoundError extends AppError {
28
55
  constructor(message = 'Resource not found', code = 'NOT_FOUND') {
29
56
  super(code, message, 404);
@@ -36,6 +63,16 @@ export class ConflictError extends AppError {
36
63
  }
37
64
  }
38
65
 
66
+ /**
67
+ * 503: a feature that depends on something temporarily down (e.g. Redis for
68
+ * password-reset and verification tokens). The request was fine; retry later.
69
+ */
70
+ export class ServiceUnavailableError extends AppError {
71
+ constructor(message = 'Service temporarily unavailable', code = 'SERVICE_UNAVAILABLE') {
72
+ super(code, message, 503);
73
+ }
74
+ }
75
+
39
76
  export class InternalError extends AppError {
40
77
  constructor(message = 'Internal server error', code = 'INTERNAL_ERROR') {
41
78
  super(code, message, 500);
@@ -6,12 +6,31 @@ export function successResponse<T>(message: string, data: T): {
6
6
  return { success: true as const, message, data };
7
7
  }
8
8
 
9
- export function errorResponse(code: string, message: string): {
9
+ import type { FieldError } from '@shared/errors/AppError.js';
10
+
11
+ /**
12
+ * Error envelope. Optional members appear only when they apply:
13
+ * - `retryAfterSeconds` when the caller can retry after a known wait (429s and
14
+ * an automatic IP block); the client uses it to say "try again in N minutes";
15
+ * - `fields` on 422 VALIDATION_FAILED: each wrong input field and why, never
16
+ * the submitted value.
17
+ */
18
+ export function errorResponse(
19
+ code: string,
20
+ message: string,
21
+ retryAfterSeconds?: number,
22
+ fields?: FieldError[],
23
+ ): {
10
24
  success: false;
11
- error: { code: string; message: string };
25
+ error: { code: string; message: string; retryAfterSeconds?: number; fields?: FieldError[] };
12
26
  } {
13
27
  return {
14
28
  success: false as const,
15
- error: { code, message },
29
+ error: {
30
+ code,
31
+ message,
32
+ ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }),
33
+ ...(fields && fields.length > 0 ? { fields } : {}),
34
+ },
16
35
  };
17
36
  }