create-tigra 3.2.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 (209) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +160 -44
  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 +81 -21
  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 +38 -19
  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 +18 -4
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
  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/features/auth/types/auth.types.ts +3 -0
  41. package/template/client/src/instrumentation-client.ts +9 -1
  42. package/template/client/src/instrumentation.ts +6 -0
  43. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  44. package/template/client/src/lib/api/api.types.ts +14 -0
  45. package/template/client/src/lib/api/axios.config.ts +101 -15
  46. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  47. package/template/client/src/lib/api/session-events.ts +29 -0
  48. package/template/client/src/lib/constants/routes.ts +12 -0
  49. package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
  50. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  51. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  52. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  53. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  54. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  55. package/template/client/src/lib/utils/error.ts +86 -1
  56. package/template/client/src/lib/utils/form.ts +31 -0
  57. package/template/client/src/lib/utils/paths.ts +18 -0
  58. package/template/client/src/lib/utils/security.ts +37 -0
  59. package/template/client/src/lib/utils/session-marker.ts +24 -0
  60. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  61. package/template/client/src/store/__tests__/store.test.ts +44 -0
  62. package/template/client/src/store/index.ts +26 -8
  63. package/template/client/vitest.config.mts +48 -0
  64. package/template/server/.env.example +280 -269
  65. package/template/server/.env.example.production +283 -236
  66. package/template/server/AGENTS.md +13 -4
  67. package/template/server/Dockerfile +181 -14
  68. package/template/server/docker-compose.yml +4 -2
  69. package/template/server/docs/deployment.md +63 -0
  70. package/template/server/docs/logging.md +52 -4
  71. package/template/server/docs/rate-limits.md +153 -0
  72. package/template/server/docs/testing.md +63 -0
  73. package/template/server/eslint.config.mjs +19 -0
  74. package/template/server/package-lock.json +8784 -8743
  75. package/template/server/package.json +79 -75
  76. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  77. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  78. package/template/server/prisma/schema.prisma +19 -6
  79. package/template/server/prisma/seed.ts +13 -5
  80. package/template/server/scripts/check-heic.mjs +40 -0
  81. package/template/server/scripts/check-sharp.mjs +53 -0
  82. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  83. package/template/server/src/app.ts +248 -335
  84. package/template/server/src/config/__tests__/env.test.ts +219 -0
  85. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  86. package/template/server/src/config/env.ts +326 -171
  87. package/template/server/src/config/rate-limit.config.ts +157 -106
  88. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
  89. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  90. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  91. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  92. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +81 -65
  93. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  94. package/template/server/src/jobs/index.ts +12 -2
  95. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  96. package/template/server/src/jobs/schedule.ts +50 -0
  97. package/template/server/src/libs/__tests__/auth.test.ts +168 -0
  98. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  99. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  100. package/template/server/src/libs/__tests__/cookies.test.ts +113 -0
  101. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  102. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  103. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  104. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  105. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  106. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  107. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  108. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  109. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  110. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  111. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  112. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  113. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  114. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  115. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  116. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  117. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  118. package/template/server/src/libs/__tests__/redis.test.ts +59 -0
  119. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  120. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  121. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  122. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -0
  123. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  124. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  125. package/template/server/src/libs/account-status.ts +52 -0
  126. package/template/server/src/libs/auth.ts +51 -12
  127. package/template/server/src/libs/client-ip.ts +158 -77
  128. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  129. package/template/server/src/libs/cookies.ts +91 -24
  130. package/template/server/src/libs/email-quota.ts +74 -0
  131. package/template/server/src/libs/email.ts +46 -9
  132. package/template/server/src/libs/error-handler.ts +111 -0
  133. package/template/server/src/libs/health-routes.ts +53 -0
  134. package/template/server/src/libs/http.ts +139 -47
  135. package/template/server/src/libs/ip-address.ts +37 -0
  136. package/template/server/src/libs/ip-block.ts +284 -220
  137. package/template/server/src/libs/logger.ts +41 -12
  138. package/template/server/src/libs/monitoring.ts +131 -42
  139. package/template/server/src/libs/observability/sentry.ts +80 -0
  140. package/template/server/src/libs/origin-check.ts +9 -7
  141. package/template/server/src/libs/prisma.ts +47 -4
  142. package/template/server/src/libs/query-counter.ts +71 -59
  143. package/template/server/src/libs/rate-limiting.ts +110 -0
  144. package/template/server/src/libs/redis-required.ts +28 -0
  145. package/template/server/src/libs/redis.ts +108 -18
  146. package/template/server/src/libs/request-id.ts +18 -0
  147. package/template/server/src/libs/requestLogger.ts +112 -17
  148. package/template/server/src/libs/safe-http.ts +101 -0
  149. package/template/server/src/libs/shutdown.ts +87 -0
  150. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  151. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +143 -0
  152. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  153. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  154. package/template/server/src/libs/storage/file-storage.service.ts +104 -83
  155. package/template/server/src/libs/storage/file-validator.ts +48 -46
  156. package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
  157. package/template/server/src/libs/token-hash.ts +18 -0
  158. package/template/server/src/libs/url-safety.ts +127 -121
  159. package/template/server/src/libs/validation-errors.ts +86 -0
  160. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  161. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  162. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  163. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  164. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  165. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  166. package/template/server/src/modules/admin/admin.repo.ts +56 -13
  167. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  168. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  169. package/template/server/src/modules/admin/admin.service.ts +73 -7
  170. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  171. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  172. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  173. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +332 -49
  174. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  175. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  176. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  177. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  178. package/template/server/src/modules/auth/auth.repo.ts +60 -42
  179. package/template/server/src/modules/auth/auth.schemas.ts +5 -2
  180. package/template/server/src/modules/auth/auth.service.ts +197 -109
  181. package/template/server/src/modules/auth/session.repo.ts +12 -12
  182. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  183. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  184. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  185. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  186. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  187. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  188. package/template/server/src/modules/users/users.controller.ts +9 -38
  189. package/template/server/src/modules/users/users.repo.ts +25 -7
  190. package/template/server/src/modules/users/users.routes.ts +3 -22
  191. package/template/server/src/modules/users/users.schemas.ts +15 -9
  192. package/template/server/src/modules/users/users.service.ts +105 -93
  193. package/template/server/src/scripts/make-admin.ts +48 -0
  194. package/template/server/src/server.ts +48 -26
  195. package/template/server/src/shared/errors/AppError.ts +27 -1
  196. package/template/server/src/shared/errors/errors.ts +42 -5
  197. package/template/server/src/shared/responses/successResponse.ts +22 -3
  198. package/template/server/src/shared/types/index.ts +7 -0
  199. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  200. package/template/server/src/test/integration-helpers.ts +343 -0
  201. package/template/server/src/test/integration-services.ts +74 -0
  202. package/template/server/src/test/integration.global-setup.ts +144 -0
  203. package/template/server/src/test/integration.setup.ts +35 -158
  204. package/template/server/src/test/setup.ts +23 -8
  205. package/template/server/tsconfig.build.json +1 -1
  206. package/template/server/tsconfig.json +1 -0
  207. package/template/server/vitest.config.ts +17 -4
  208. package/template/server/vitest.integration.config.ts +18 -13
  209. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -5,13 +5,12 @@
5
5
  */
6
6
 
7
7
  import type { FastifyRequest, FastifyReply } from 'fastify';
8
- import path from 'path';
9
8
  import { usersService } from './users.service.js';
10
9
  import { validateImageFile, validateFileSize } from '@libs/storage/file-validator.js';
11
10
  import { successResponse } from '@shared/responses/successResponse.js';
12
11
  import { clearAuthCookies } from '@libs/cookies.js';
13
12
  import { ChangePasswordSchema, AdminChangePasswordSchema, DeleteAccountSchema } from './users.schemas.js';
14
- import type { GetUserAvatarParams, UpdateProfileInput } from './users.schemas.js';
13
+ import type { UpdateProfileInput } from './users.schemas.js';
15
14
  import type { AuthenticatedRequest } from '@shared/types/index.js';
16
15
  import { logger } from '@libs/logger.js';
17
16
  import { BadRequestError } from '@shared/errors/errors.js';
@@ -40,14 +39,15 @@ class UsersController {
40
39
  throw new BadRequestError('No file uploaded', 'NO_FILE');
41
40
  }
42
41
 
43
- // Validate file (MIME type, extension)
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
44
  validateImageFile(data);
45
45
 
46
46
  // Read file buffer
47
47
  const buffer = await data.toBuffer();
48
48
 
49
- // Validate file size
50
- validateFileSize(buffer);
49
+ // Validate file size, including a file the parser silently cut at the limit
50
+ validateFileSize(buffer, data.file.truncated);
51
51
 
52
52
  // Get target user ID (set by resolveMe or resolveTargetUser middleware)
53
53
  const userId = request.targetUserId!;
@@ -61,13 +61,9 @@ class UsersController {
61
61
  });
62
62
 
63
63
  // Call service to process and save avatar
64
- const updatedUser = await usersService.uploadAvatar(userId, buffer, data.filename);
64
+ const { avatarUrl } = await usersService.uploadAvatar(userId, buffer, data.filename);
65
65
 
66
- return reply.send(
67
- successResponse('Avatar uploaded successfully', {
68
- avatarUrl: updatedUser.avatarUrl,
69
- })
70
- );
66
+ return reply.send(successResponse('Avatar uploaded successfully', { avatarUrl }));
71
67
  }
72
68
 
73
69
  /**
@@ -91,32 +87,6 @@ class UsersController {
91
87
  return reply.send(successResponse('Avatar deleted successfully', null));
92
88
  }
93
89
 
94
- /**
95
- * Get avatar handler
96
- *
97
- * GET /api/v1/users/:userId/avatar
98
- * Auth: Not required (public endpoint)
99
- *
100
- * Returns the avatar file directly or 404 if not found.
101
- *
102
- * @param request - Fastify request
103
- * @param reply - Fastify reply
104
- */
105
- async getAvatar(
106
- request: FastifyRequest<{ Params: GetUserAvatarParams }>,
107
- reply: FastifyReply
108
- ): Promise<void> {
109
- const { userId } = request.params;
110
-
111
- logger.info({ msg: 'Avatar fetch request', userId });
112
-
113
- // Get avatar file path
114
- const { path: filePath } = await usersService.getAvatar(userId);
115
-
116
- // Send file directly
117
- return reply.sendFile(path.basename(filePath), path.dirname(filePath));
118
- }
119
-
120
90
  /**
121
91
  * Update profile handler
122
92
  *
@@ -163,7 +133,8 @@ class UsersController {
163
133
  } else {
164
134
  const parsed = ChangePasswordSchema.parse(request.body);
165
135
  logger.info({ msg: 'Change password request', userId });
166
- await usersService.changePassword(userId, parsed, false);
136
+ // Keep the device that asked signed in; every other session ends.
137
+ await usersService.changePassword(userId, parsed, false, request.user.sessionId);
167
138
  }
168
139
 
169
140
  return reply.send(successResponse('Password changed successfully', null));
@@ -18,6 +18,7 @@ const userSelect = {
18
18
  role: true,
19
19
  avatarUrl: true,
20
20
  isActive: true,
21
+ emailVerifiedAt: true,
21
22
  createdAt: true,
22
23
  updatedAt: true,
23
24
  } as const;
@@ -30,6 +31,7 @@ export type SafeUser = {
30
31
  role: UserRole;
31
32
  avatarUrl: string | null;
32
33
  isActive: boolean;
34
+ emailVerifiedAt: Date | null;
33
35
  createdAt: Date;
34
36
  updatedAt: Date;
35
37
  };
@@ -51,14 +53,18 @@ class UsersRepository {
51
53
  }
52
54
 
53
55
  /**
54
- * Updates a user's avatar URL
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.
55
61
  */
56
- async updateUserAvatar(userId: string, avatarUrl: string): Promise<SafeUser> {
57
- return prisma.user.update({
58
- where: { id: userId },
59
- data: { avatarUrl },
60
- select: userSelect,
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 },
61
66
  });
67
+ return count === 1;
62
68
  }
63
69
 
64
70
  /**
@@ -87,7 +93,18 @@ class UsersRepository {
87
93
  }
88
94
 
89
95
  /**
90
- * Soft deletes a user by setting deletedAt and isActive = false
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
+ });
103
+ }
104
+
105
+ /**
106
+ * Soft deletes a user: deletedAt set, isActive = false, and the avatar URL
107
+ * cleared (its file is removed right after, see usersService.deleteAccount).
91
108
  */
92
109
  async softDeleteUser(userId: string): Promise<void> {
93
110
  await prisma.user.update({
@@ -95,6 +112,7 @@ class UsersRepository {
95
112
  data: {
96
113
  deletedAt: new Date(),
97
114
  isActive: false,
115
+ avatarUrl: null,
98
116
  },
99
117
  });
100
118
  }
@@ -7,7 +7,6 @@
7
7
  import type { FastifyInstance } from 'fastify';
8
8
  import { usersController } from './users.controller.js';
9
9
  import {
10
- GetUserAvatarSchema,
11
10
  UserIdParamSchema,
12
11
  UpdateProfileSchema,
13
12
  ChangePasswordSchema,
@@ -25,13 +24,15 @@ import { RATE_LIMITS } from '@config/rate-limit.config.js';
25
24
  * - DELETE /users/me - Delete account (authenticated)
26
25
  * - POST /users/avatar - Upload avatar (authenticated)
27
26
  * - DELETE /users/avatar - Delete avatar (authenticated)
28
- * - GET /users/:userId/avatar - Get avatar (public)
29
27
  * - PATCH /users/:userId - Update profile (owner or admin)
30
28
  * - PATCH /users/:userId/password - Change password (owner or admin)
31
29
  * - DELETE /users/:userId - Delete account (owner or admin)
32
30
  * - POST /users/:userId/avatar - Upload avatar (owner or admin)
33
31
  * - DELETE /users/:userId/avatar - Delete avatar (owner or admin)
34
32
  *
33
+ * Avatars are read from their public URL (/uploads/users/{id}/avatar/...,
34
+ * served statically by app.ts), never through a /users route.
35
+ *
35
36
  * @param fastify - Fastify instance
36
37
  */
37
38
  export async function usersRoutes(fastify: FastifyInstance): Promise<void> {
@@ -143,26 +144,6 @@ export async function usersRoutes(fastify: FastifyInstance): Promise<void> {
143
144
  usersController.deleteAvatar.bind(usersController)
144
145
  );
145
146
 
146
- /**
147
- * Get user avatar
148
- *
149
- * GET /api/v1/users/:userId/avatar
150
- * Auth: Not required (public)
151
- * Rate limit: 100 requests per minute per IP
152
- */
153
- fastify.get<{ Params: { userId: string } }>(
154
- '/users/:userId/avatar',
155
- {
156
- schema: {
157
- params: GetUserAvatarSchema,
158
- },
159
- config: {
160
- rateLimit: RATE_LIMITS.USERS_GET_AVATAR,
161
- },
162
- },
163
- usersController.getAvatar.bind(usersController)
164
- );
165
-
166
147
  // --- /users/:userId variants (owner or admin) ---
167
148
 
168
149
  /**
@@ -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
+ });