create-tigra 4.1.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -1
  3. package/bin/create-tigra.js +68 -73
  4. package/lib/installer-transaction.js +275 -0
  5. package/lib/patchers/diagnostics.patcher.js +33 -59
  6. package/lib/patchers/email-verification.patcher.js +86 -92
  7. package/lib/patchers/metrics.patcher.js +18 -18
  8. package/lib/project-files.js +99 -0
  9. package/modules/diagnostics/diagnostics.md +10 -0
  10. package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
  11. package/modules/diagnostics/prisma/migration.sql +1 -24
  12. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
  13. package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
  14. package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
  15. package/modules/email-verification/client/hooks/useVerification.ts +4 -7
  16. package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
  17. package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
  18. package/modules/email-verification/server/verification.service.ts +102 -157
  19. package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
  20. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
  21. package/modules/metrics/performance.md +2 -2
  22. package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
  23. package/modules/metrics/server/metrics.collector.ts +6 -3
  24. package/modules/metrics/server/metrics.routes.ts +1 -2
  25. package/modules/metrics/server/metrics.service.ts +6 -2
  26. package/package.json +1 -1
  27. package/template/AGENTS.md +4 -3
  28. package/template/client/.dockerignore +2 -5
  29. package/template/client/gitignore +43 -0
  30. package/template/client/package-lock.json +51 -51
  31. package/template/client/package.json +2 -2
  32. package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
  33. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  34. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  35. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  36. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  37. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  38. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  39. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  40. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  41. package/template/client/src/lib/api/axios.config.ts +24 -6
  42. package/template/client/src/lib/api/session-events.ts +54 -0
  43. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  44. package/template/client/src/store/__tests__/store.test.ts +1 -0
  45. package/template/gitignore +3 -2
  46. package/template/server/.dockerignore +2 -5
  47. package/template/server/.env.example +1 -0
  48. package/template/server/.env.example.production +1 -0
  49. package/template/server/README.md +7 -2
  50. package/template/server/docs/deployment.md +66 -0
  51. package/template/server/docs/logging.md +9 -8
  52. package/template/server/docs/rate-limits.md +6 -4
  53. package/template/server/gitignore +33 -0
  54. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  55. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  56. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  57. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  58. package/template/server/prisma/schema.prisma +25 -1
  59. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  60. package/template/server/src/app.ts +14 -5
  61. package/template/server/src/config/env.ts +8 -0
  62. package/template/server/src/config/rate-limit.config.ts +1 -1
  63. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  64. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  65. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  66. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  67. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  68. package/template/server/src/jobs/index.ts +8 -2
  69. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  70. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  71. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  72. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  73. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  74. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  75. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  76. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  77. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  78. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  79. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  80. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  81. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  82. package/template/server/src/libs/account-mutation.ts +77 -0
  83. package/template/server/src/libs/auth.ts +37 -3
  84. package/template/server/src/libs/cookies.ts +25 -13
  85. package/template/server/src/libs/email-quota.ts +11 -7
  86. package/template/server/src/libs/email.ts +11 -8
  87. package/template/server/src/libs/error-handler.ts +16 -12
  88. package/template/server/src/libs/http.ts +37 -13
  89. package/template/server/src/libs/ip-block.ts +56 -34
  90. package/template/server/src/libs/logger.ts +23 -8
  91. package/template/server/src/libs/monitoring.ts +57 -31
  92. package/template/server/src/libs/observability/sentry.ts +65 -49
  93. package/template/server/src/libs/prisma.ts +1 -1
  94. package/template/server/src/libs/private-cache.ts +6 -0
  95. package/template/server/src/libs/rate-limiting.ts +4 -0
  96. package/template/server/src/libs/requestLogger.ts +3 -3
  97. package/template/server/src/libs/safe-http.ts +58 -18
  98. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  99. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  100. package/template/server/src/libs/storage/file-validator.ts +2 -1
  101. package/template/server/src/libs/url-safety.ts +10 -2
  102. package/template/server/src/libs/validation-errors.ts +11 -8
  103. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  104. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  105. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  106. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  107. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  108. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  109. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  110. package/template/server/src/modules/admin/admin.service.ts +61 -62
  111. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  112. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  113. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  114. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  115. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  116. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  117. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  118. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  119. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  120. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  121. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  122. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  123. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  124. package/template/server/src/modules/auth/auth.service.ts +33 -237
  125. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  126. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  127. package/template/server/src/modules/auth/session.repo.ts +5 -4
  128. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  129. package/template/server/src/modules/files/files.controller.ts +2 -2
  130. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  131. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  132. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  133. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  134. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  135. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  136. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  137. package/template/server/src/modules/users/users.controller.ts +28 -25
  138. package/template/server/src/modules/users/users.repo.ts +12 -51
  139. package/template/server/src/modules/users/users.service.ts +109 -234
  140. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  141. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  142. package/template/server/src/test/setup.ts +4 -0
@@ -18,10 +18,9 @@
18
18
  *
19
19
  * ── Public files never change under the same name ──────────────────────────
20
20
  * Every new avatar gets a NEW random filename, so a URL always means the same
21
- * bytes. That is what lets app.ts serve /uploads with a one-year immutable
22
- * cache, and it keeps any cache keyed by URL (browsers, CDNs, the Next.js image
23
- * optimizer) from showing an old photo. Anything else stored in the public
24
- * tier must follow the same rule: new content, new name.
21
+ * bytes. Publishing under a fresh URL also lets replicas remove the previous
22
+ * file without touching its replacement. Other public assets use immutable
23
+ * caching and must follow the same rule: new content, new name.
25
24
  */
26
25
 
27
26
  import { randomBytes } from 'node:crypto';
@@ -32,6 +31,27 @@ import { env } from '@config/env.js';
32
31
  import { logger } from '@libs/logger.js';
33
32
  import { InternalError } from '@shared/errors/errors.js';
34
33
 
34
+ export interface AvatarFile {
35
+ userId: string;
36
+ filename: string;
37
+ }
38
+
39
+ export function avatarFileUrl({ userId, filename }: AvatarFile): string {
40
+ return `/uploads/users/${userId}/avatar/${filename}`;
41
+ }
42
+
43
+ function validAvatarFilename(filename: string): boolean {
44
+ return /^[\p{L}\p{N}_-][\p{L}\p{N}_.-]*\.webp$/u.test(filename);
45
+ }
46
+
47
+ /** Only accept the stored URL for an exact avatar file owned by this account. */
48
+ export function avatarFileFromUrl(userId: string, url: string | null): AvatarFile | null {
49
+ if (!url) return null;
50
+ const filename = path.posix.basename(url);
51
+ const file = { userId, filename };
52
+ return validAvatarFilename(filename) && url === avatarFileUrl(file) ? file : null;
53
+ }
54
+
35
55
  /** How uploadDirsOnContainerDisk looks at the disk (injectable for tests). */
36
56
  export interface DiskProbe {
37
57
  exists(p: string): boolean;
@@ -131,74 +151,41 @@ class FileStorageService {
131
151
  return path.join(this.getUserDir(userId), 'avatar');
132
152
  }
133
153
 
134
- /**
135
- * Writes a NEW avatar file under a fresh random name and returns its URL.
136
- *
137
- * It never overwrites or deletes anything: the old avatar keeps serving until
138
- * the database points at the new one, and the caller then removes exactly
139
- * the file it replaced (see usersService.uploadAvatar). The name carries no
140
- * personal data (no user name) and is unique per upload.
141
- *
142
- * @param userId - User's unique ID
143
- * @param buffer - Optimized image buffer (always WebP)
144
- * @returns Filename and public URL, e.g. /uploads/users/{userId}/avatar/avatar-3f9c0a1b2c3d4e5f.webp
145
- */
146
- async saveAvatar(userId: string, buffer: Buffer): Promise<{ filename: string; url: string }> {
147
- try {
148
- const avatarDir = this.getUserAvatarDir(userId);
149
- await this.ensureDirectoryExists(avatarDir);
150
-
151
- const filename = `avatar-${randomBytes(8).toString('hex')}.webp`;
152
- await fs.writeFile(path.join(avatarDir, filename), buffer);
153
-
154
- const url = `/uploads/users/${userId}/avatar/${filename}`;
155
-
156
- logger.info({
157
- msg: 'Avatar saved successfully',
158
- userId,
159
- filename,
160
- fileSize: buffer.length,
161
- });
154
+ allocateAvatar(userId: string): AvatarFile {
155
+ return { userId, filename: `avatar-${randomBytes(8).toString('hex')}.webp` };
156
+ }
162
157
 
163
- return { filename, url };
158
+ /** Rename only a complete optimized image, on the same volume as its final URL. */
159
+ async publishAvatar(file: AvatarFile, buffer: Buffer): Promise<void> {
160
+ const { image, temporary, dir } = this.avatarPaths(file);
161
+ try {
162
+ await this.ensureDirectoryExists(dir);
163
+ await fs.writeFile(temporary, buffer, { flag: 'wx' });
164
+ await fs.rename(temporary, image);
164
165
  } catch (error) {
165
- logger.error({ err: error, msg: 'Failed to save avatar', userId });
166
+ logger.error({ err: error, userId: file.userId, msg: 'Failed to publish avatar' });
166
167
  throw new InternalError('Failed to save avatar file', 'FILE_SAVE_FAILED');
167
168
  }
168
169
  }
169
170
 
170
- /**
171
- * Deletes a user's avatar directory and all contents
172
- *
173
- * @param userId - User's unique ID
174
- * @throws InternalError if deletion fails
175
- *
176
- * @example
177
- * ```typescript
178
- * await fileStorageService.deleteAvatar(userId);
179
- * ```
180
- */
181
- async deleteAvatar(userId: string): Promise<void> {
171
+ /** Only the queued file and its temporary sibling belong to this operation. */
172
+ async removeAvatarFile(file: AvatarFile): Promise<void> {
173
+ const { image, temporary, dir } = this.avatarPaths(file);
174
+ await fs.rm(image, { force: true });
175
+ await fs.rm(temporary, { force: true });
182
176
  try {
183
- const avatarDir = this.getUserAvatarDir(userId);
184
-
185
- // Check if directory exists
186
- const exists = await this.directoryExists(avatarDir);
187
- if (!exists) {
188
- logger.info({ msg: 'Avatar directory does not exist, nothing to delete', userId });
189
- return;
190
- }
191
-
192
- // Delete avatar directory and contents
193
- await fs.rm(avatarDir, { recursive: true, force: true });
194
-
195
- logger.info({ msg: 'Avatar deleted successfully', userId });
177
+ await fs.rmdir(dir);
196
178
  } catch (error) {
197
- logger.error({ err: error, msg: 'Failed to delete avatar', userId });
198
- throw new InternalError('Failed to delete avatar file', 'FILE_DELETE_FAILED');
179
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;
199
180
  }
200
181
  }
201
182
 
183
+ private avatarPaths(file: AvatarFile): { image: string; temporary: string; dir: string } {
184
+ if (!validAvatarFilename(file.filename)) throw new Error('Invalid stored avatar filename');
185
+ const dir = this.getUserAvatarDir(file.userId);
186
+ return { dir, image: path.join(dir, file.filename), temporary: path.join(dir, `.${file.filename}.tmp`) };
187
+ }
188
+
202
189
  /**
203
190
  * Deletes all media for a user: the public directory (avatars) AND the
204
191
  * private directory (owner-only files).
@@ -218,9 +205,9 @@ class FileStorageService {
218
205
  async deleteUserMedia(userId: string): Promise<void> {
219
206
  try {
220
207
  for (const dir of [this.getUserDir(userId), this.getUserPrivateDir(userId)]) {
221
- if (await this.directoryExists(dir)) {
222
- await fs.rm(dir, { recursive: true, force: true });
223
- }
208
+ // force tolerates missing media. Other filesystem errors must reach
209
+ // the purge worker so it keeps the retry record in MySQL.
210
+ await fs.rm(dir, { recursive: true, force: true });
224
211
  }
225
212
 
226
213
  logger.info({ msg: 'User media deleted successfully', userId });
@@ -230,24 +217,6 @@ class FileStorageService {
230
217
  }
231
218
  }
232
219
 
233
- /**
234
- * Removes ONE avatar file of this user. Best effort: never throws, because it
235
- * runs while cleaning up (the replaced file after a new upload, or the new
236
- * file after a failed one). A miss is logged; the account purge removes any
237
- * leftover with the whole folder.
238
- *
239
- * Only the basename is used, so whatever a stored URL says, the path stays
240
- * inside this user's avatar folder.
241
- */
242
- async removeAvatarFile(userId: string, filename: string): Promise<void> {
243
- const safeName = path.basename(filename);
244
- try {
245
- await fs.rm(path.join(this.getUserAvatarDir(userId), safeName), { force: true });
246
- } catch (error) {
247
- logger.error({ err: error, msg: 'Failed to remove avatar file', userId, filename: safeName });
248
- }
249
- }
250
-
251
220
  /**
252
221
  * Sanitizes a single-segment filename for safe disk storage.
253
222
  *
@@ -256,21 +225,17 @@ class FileStorageService {
256
225
  * escape the user's private directory. This is a storage-side guard; the
257
226
  * files route applies its OWN validation + path-containment check on read.
258
227
  *
259
- * @throws InternalError on an empty or unusable name
228
+ * Returns null for an unusable name so reads can answer 404.
260
229
  */
261
- private sanitizePrivateFilename(filename: string): string {
230
+ private sanitizePrivateFilename(filename: string): string | null {
262
231
  // Reject obvious traversal/separator/null-byte input up front.
263
232
  if (!filename || filename.includes('\0') || filename.includes('/') || filename.includes('\\')) {
264
- throw new InternalError('Invalid private filename', 'INVALID_FILENAME');
233
+ return null;
265
234
  }
266
235
  // Collapse to the basename and drop any leading dots so `..`/`.` can't slip
267
236
  // through; keep a conservative allowlist (letters, digits, . _ -).
268
237
  const base = path.basename(filename).replace(/^\.+/, '');
269
- const cleaned = base.replace(/[^a-zA-Z0-9._-]/g, '');
270
- if (!cleaned) {
271
- throw new InternalError('Invalid private filename', 'INVALID_FILENAME');
272
- }
273
- return cleaned;
238
+ return base.replace(/[^a-zA-Z0-9._-]/g, '') || null;
274
239
  }
275
240
 
276
241
  /**
@@ -292,6 +257,7 @@ class FileStorageService {
292
257
  ): Promise<{ filename: string; path: string }> {
293
258
  try {
294
259
  const safeName = this.sanitizePrivateFilename(filename);
260
+ if (!safeName) throw new InternalError('Invalid private filename', 'INVALID_FILENAME');
295
261
  const userDir = this.getUserPrivateDir(userId);
296
262
  await this.ensureDirectoryExists(userDir);
297
263
 
@@ -323,11 +289,11 @@ class FileStorageService {
323
289
  *
324
290
  * @param userId - User's unique ID (the owner)
325
291
  * @param filename - File name within the user's private directory
326
- * @returns Absolute file path under UPLOAD_PRIVATE_DIR/users/{userId}/
292
+ * @returns An owner-scoped absolute path, or null for an unusable name
327
293
  */
328
- getPrivateFilePath(userId: string, filename: string): string {
294
+ getPrivateFilePath(userId: string, filename: string): string | null {
329
295
  const safeName = this.sanitizePrivateFilename(filename);
330
- return path.join(this.getUserPrivateDir(userId), safeName);
296
+ return safeName ? path.join(this.getUserPrivateDir(userId), safeName) : null;
331
297
  }
332
298
 
333
299
  /**
@@ -346,22 +312,6 @@ class FileStorageService {
346
312
  }
347
313
  }
348
314
 
349
- /**
350
- * Checks if a directory exists
351
- *
352
- * @param dirPath - Directory path
353
- * @returns True if directory exists
354
- * @private
355
- */
356
- private async directoryExists(dirPath: string): Promise<boolean> {
357
- try {
358
- const stats = await fs.stat(dirPath);
359
- return stats.isDirectory();
360
- } catch {
361
- return false;
362
- }
363
- }
364
-
365
315
  /**
366
316
  * Initializes the upload directory structure
367
317
  *
@@ -31,7 +31,8 @@ export const FILE_UPLOAD_CONSTANTS = {
31
31
  * is free) can send that to the avatar upload. Proven live: 300 fields of 1 MB
32
32
  * grew the server by 429 MB. These caps bound it to about 2 MB:
33
33
  * - more fields or parts than allowed: 413 MULTIPART_LIMIT (libs/error-handler.ts);
34
- * - a field longer than fieldSize is truncated, never buffered whole.
34
+ * - a field longer than fieldSize is truncated, never buffered whole. The
35
+ * avatar handler rejects a truncated field before publishing an image.
35
36
  * Raise them only for a route that really sends many or large fields.
36
37
  */
37
38
  export const MULTIPART_LIMITS = {
@@ -43,7 +43,7 @@ export function redactUrl(url: string): string {
43
43
 
44
44
  // Drop the query string (and fragment) — may hold API keys or signed tokens —
45
45
  // and credentials in the authority (https://user:password@host/).
46
- const noQuery = url.split(/[?#]/, 1)[0].replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, '$1');
46
+ const noQuery = url.split(/[?#]/, 1)[0].replace(/^((?:[a-z][a-z0-9+.-]*:)?\/\/)[^/]*@/i, '$1');
47
47
 
48
48
  // Rewrite Telegram bot-token path segments. The token charset is [A-Za-z0-9_-]
49
49
  // plus the ':' separating bot-id from secret, e.g. 123456:AAH...
@@ -87,10 +87,16 @@ for (const [net, prefix] of [
87
87
  ['2001::', 23], // IETF protocol assignments (incl. Teredo)
88
88
  ['2001:db8::', 32], // documentation
89
89
  ['2002::', 16], // 6to4: embeds an IPv4 address
90
+ ['3fff::', 20], // documentation (RFC 9637)
90
91
  ['fec0::', 10], // site-local (deprecated)
91
92
  ['ff00::', 8], // multicast
92
93
  ] as const) NOT_PUBLIC.addSubnet(net, prefix, 'ipv6');
93
94
 
95
+ // IANA's global unicast allocation. Special-purpose blocks inside it still
96
+ // need the exclusions above. IPv4-mapped addresses are classified as IPv4.
97
+ const IPV6_GLOBAL_UNICAST = new BlockList();
98
+ IPV6_GLOBAL_UNICAST.addSubnet('2000::', 3, 'ipv6');
99
+
94
100
  /** Canonical address and its family, or undefined for anything that is not an IP literal. */
95
101
  function parse(addr: unknown): { ip: string; family: 'ipv4' | 'ipv6' } | undefined {
96
102
  if (typeof addr !== 'string') return undefined;
@@ -123,5 +129,7 @@ export function isPrivateOrReservedIp(addr: string): boolean {
123
129
  export function isForbiddenOutboundIp(addr: string): boolean {
124
130
  const parsed = parse(addr);
125
131
  if (!parsed) return true;
126
- return INTERNAL.check(parsed.ip, parsed.family) || NOT_PUBLIC.check(parsed.ip, parsed.family);
132
+ return (parsed.family === 'ipv6' && !IPV6_GLOBAL_UNICAST.check(parsed.ip, 'ipv6'))
133
+ || INTERNAL.check(parsed.ip, parsed.family)
134
+ || NOT_PUBLIC.check(parsed.ip, parsed.family);
127
135
  }
@@ -7,11 +7,8 @@
7
7
  * message: 'Please check these fields: email, password',
8
8
  * fields: [{ field: 'email', message: 'Invalid email address' }, ...] } }
9
9
  *
10
- * Never the submitted values: messages come from Zod (or Ajv), which describe
11
- * the rule ("Too small: expected string to have >=8 characters"), and Zod
12
- * drops an issue's `input` unless `reportInput` is set, which nothing here
13
- * does. Keep it that way: a value in a validation answer can leak a password
14
- * into logs, screenshots or a support ticket.
10
+ * Keep messages about the rule. Strict-object validators can include submitted
11
+ * key names, so replace that message before exposing it to an API caller.
15
12
  *
16
13
  * Malformed JSON is not "wrong input" but an unreadable request; it stays a
17
14
  * 400 BAD_REQUEST in libs/error-handler.ts.
@@ -28,6 +25,7 @@ export const MAX_FIELD_ERRORS = 20;
28
25
  interface IssueLike {
29
26
  path: ReadonlyArray<PropertyKey>;
30
27
  message: string;
28
+ code?: string;
31
29
  }
32
30
 
33
31
  /** Fastify's names for the request parts, shown when the whole part is wrong. */
@@ -37,11 +35,16 @@ function partName(context: string | undefined): string {
37
35
  return (context && PART_NAMES[context]) ?? 'input';
38
36
  }
39
37
 
38
+ function safeMessage(code: string | undefined, message: string | undefined): string {
39
+ if (code === 'unrecognized_keys' || code === 'additionalProperties') return 'Unexpected fields';
40
+ return message ?? 'Invalid value';
41
+ }
42
+
40
43
  /** Zod issues (from `.parse()` / `.safeParse()`) as field errors. */
41
44
  export function fieldsFromZodIssues(issues: ReadonlyArray<IssueLike>, context?: string): FieldError[] {
42
45
  return issues.slice(0, MAX_FIELD_ERRORS).map((issue) => ({
43
46
  field: issue.path.length > 0 ? issue.path.map(String).join('.') : partName(context),
44
- message: issue.message,
47
+ message: safeMessage(issue.code, issue.message),
45
48
  }));
46
49
  }
47
50
 
@@ -52,12 +55,12 @@ export function fieldsFromZodIssues(issues: ReadonlyArray<IssueLike>, context?:
52
55
  * params, body, querystring, headers in that order and stops at the first).
53
56
  */
54
57
  export function fieldsFromSchemaValidation(
55
- validation: ReadonlyArray<{ instancePath?: string; message?: string }>,
58
+ validation: ReadonlyArray<{ instancePath?: string; message?: string; keyword?: string }>,
56
59
  context?: string,
57
60
  ): FieldError[] {
58
61
  return validation.slice(0, MAX_FIELD_ERRORS).map((item) => {
59
62
  const path = (item.instancePath ?? '').split('/').filter(Boolean).join('.');
60
- return { field: path || partName(context), message: item.message ?? 'Invalid value' };
63
+ return { field: path || partName(context), message: safeMessage(item.keyword, item.message) };
61
64
  });
62
65
  }
63
66
 
@@ -10,7 +10,7 @@ import { adminRepository } from '../admin.repo.js';
10
10
  vi.mock('@libs/prisma.js', () => ({
11
11
  prisma: {
12
12
  user: { findMany: vi.fn(), findUnique: vi.fn(), count: vi.fn(), updateMany: vi.fn() },
13
- session: { findFirst: vi.fn() },
13
+ session: { findFirst: vi.fn(), deleteMany: vi.fn() },
14
14
  },
15
15
  isPrismaNotFound: (): boolean => false,
16
16
  }));
@@ -34,16 +34,33 @@ describe('adminRepository', () => {
34
34
  expect(vi.mocked(prisma.user.findMany).mock.calls[0]?.[0]?.where).toMatchObject({ deletedAt: { not: null } });
35
35
  });
36
36
 
37
+ it('searches for literal characters in name and email filters', async () => {
38
+ await adminRepository.getUsers({ ...list, search: '100%_complete' });
39
+ const contains = '100\\%\\_complete';
40
+ const where = { OR: [{ email: { contains } }, { firstName: { contains } }, { lastName: { contains } }] };
41
+ expect(prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining(where) }));
42
+ expect(prisma.user.count).toHaveBeenCalledWith({ where: expect.objectContaining(where) });
43
+ });
44
+
37
45
  it('restore is one conditional update that touches only a deleted row', async () => {
38
46
  vi.mocked(prisma.user.updateMany).mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
39
- await expect(adminRepository.restoreUser('u1')).resolves.toBe(true);
40
- await expect(adminRepository.restoreUser('u1')).resolves.toBe(false);
47
+ await expect(adminRepository.restoreUser(prisma, 'u1')).resolves.toBe(true);
48
+ await expect(adminRepository.restoreUser(prisma, 'u1')).resolves.toBe(false);
41
49
  expect(prisma.user.updateMany).toHaveBeenCalledWith({
42
- where: { id: 'u1', deletedAt: { not: null } },
50
+ where: { id: 'u1', deletedAt: { not: null }, purgeStartedAt: null },
43
51
  data: { deletedAt: null, isActive: true },
44
52
  });
45
53
  });
46
54
 
55
+ it('reports deletion only when the selected session is still live', async () => {
56
+ vi.mocked(prisma.session.deleteMany).mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
57
+ await expect(adminRepository.deleteLiveSession(prisma, 's1')).resolves.toBe(true);
58
+ await expect(adminRepository.deleteLiveSession(prisma, 's1')).resolves.toBe(false);
59
+ expect(prisma.session.deleteMany).toHaveBeenCalledWith({
60
+ where: { id: 's1', expiresAt: { gt: expect.any(Date) } },
61
+ });
62
+ });
63
+
47
64
  it('user detail reports lastActiveAt (the latest still-existing session), not lastLogin', async () => {
48
65
  const seen = new Date('2026-10-19T08:00:00Z');
49
66
  vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'u1', _count: { sessions: 2 } } as never);
@@ -5,6 +5,7 @@
5
5
  * from the first parse failed the "true"/"false" check of the second).
6
6
  */
7
7
  import { describe, expect, it } from 'vitest';
8
+ import { paginatedResponse } from '@shared/responses/paginatedResponse.js';
8
9
  import { getSessionsQuerySchema, getUsersQuerySchema } from '../admin.schemas.js';
9
10
 
10
11
  const twice = <T>(schema: { parse: (v: unknown) => T }, input: unknown): { once: T; again: T } => {
@@ -35,4 +36,14 @@ describe('admin query schemas survive the second parse', () => {
35
36
  const { once, again } = twice(getSessionsQuerySchema, { page: '3', userId: '22222222-2222-4222-8222-222222222222' });
36
37
  expect(again).toEqual(once);
37
38
  });
39
+
40
+ it.each([getUsersQuerySchema, getSessionsQuerySchema])('bounds admin list pages', (schema) => {
41
+ expect(schema.safeParse({ page: '1000', limit: '100' }).success).toBe(true);
42
+ expect(schema.safeParse({ page: '1001', limit: '100' }).success).toBe(false);
43
+ });
44
+
45
+ it('reports the last accessible page while keeping the complete result count', () => {
46
+ const { pagination } = paginatedResponse('Fixture', [], 1000, 10, 10_001).data;
47
+ expect(pagination).toMatchObject({ totalItems: 10_001, totalPages: 1000, hasNextPage: false });
48
+ });
38
49
  });
@@ -7,16 +7,24 @@
7
7
  import { beforeEach, describe, expect, it, vi } from 'vitest';
8
8
  import { adminService } from '../admin.service.js';
9
9
  import { adminRepository } from '../admin.repo.js';
10
- import { sessionRepository } from '@modules/auth/session.repo.js';
11
- import { deleteRefreshTokensByUserId } from '@modules/auth/auth.repo.js';
10
+ import { prisma } from '@libs/prisma.js';
11
+
12
+ const tx = vi.hoisted(() => ({
13
+ user: { findUnique: vi.fn(), count: vi.fn() },
14
+ session: { findFirst: vi.fn(), deleteMany: vi.fn() },
15
+ refreshToken: { deleteMany: vi.fn() },
16
+ }));
12
17
 
13
18
  vi.mock('../admin.repo.js');
14
- vi.mock('@modules/auth/session.repo.js');
15
- vi.mock('@modules/auth/auth.repo.js');
19
+ vi.mock('@libs/prisma.js', () => ({
20
+ prisma: { $transaction: vi.fn() },
21
+ isPrismaWriteConflict: (error: unknown): boolean => (error as { code?: string })?.code === 'P2034',
22
+ }));
16
23
  vi.mock('@libs/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
17
24
 
18
25
  const ADMIN_ID = '11111111-1111-4111-8111-111111111111';
19
26
  const USER_ID = '22222222-2222-4222-8222-222222222222';
27
+ const actor = { userId: ADMIN_ID, sessionId: 'actor-session' };
20
28
 
21
29
  function adminUser(overrides: Record<string, unknown> = {}): never {
22
30
  return {
@@ -27,7 +35,12 @@ function adminUser(overrides: Record<string, unknown> = {}): never {
27
35
  }
28
36
 
29
37
  beforeEach(() => {
30
- vi.clearAllMocks();
38
+ vi.resetAllMocks();
39
+ vi.mocked(prisma.$transaction).mockImplementation(write => write(tx as never));
40
+ tx.user.findUnique.mockResolvedValue(adminUser({ id: ADMIN_ID, role: 'ADMIN' }));
41
+ tx.user.count.mockResolvedValue(1);
42
+ tx.session.findFirst.mockResolvedValue({ id: actor.sessionId });
43
+ tx.session.deleteMany.mockResolvedValue({ count: 1 });
31
44
  vi.mocked(adminRepository.findUserById).mockResolvedValue(adminUser());
32
45
  vi.mocked(adminRepository.updateUserStatus).mockResolvedValue(adminUser());
33
46
  vi.mocked(adminRepository.updateUserRole).mockResolvedValue(adminUser());
@@ -35,67 +48,89 @@ beforeEach(() => {
35
48
 
36
49
  describe('ban and unban', () => {
37
50
  it("banning another user ends that user's sessions and refresh tokens", async () => {
38
- await adminService.toggleUserStatus(USER_ID, false, ADMIN_ID);
39
- expect(adminRepository.updateUserStatus).toHaveBeenCalledWith(USER_ID, false, false);
40
- expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(USER_ID);
41
- expect(deleteRefreshTokensByUserId).toHaveBeenCalledWith(USER_ID);
51
+ await adminService.toggleUserStatus(USER_ID, false, actor);
52
+ expect(adminRepository.updateUserStatus).toHaveBeenCalledWith(tx, USER_ID, false, false);
53
+ expect(tx.session.deleteMany).toHaveBeenCalledWith({ where: { userId: USER_ID } });
54
+ expect(tx.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { userId: USER_ID } });
42
55
  });
43
56
 
44
57
  it('an admin cannot ban themselves (403 CANNOT_BAN_SELF), and nothing changes', async () => {
45
- await expect(adminService.toggleUserStatus(ADMIN_ID, false, ADMIN_ID)).rejects.toMatchObject({
58
+ await expect(adminService.toggleUserStatus(ADMIN_ID, false, actor)).rejects.toMatchObject({
46
59
  statusCode: 403,
47
60
  code: 'CANNOT_BAN_SELF',
48
61
  });
49
62
  expect(adminRepository.updateUserStatus).not.toHaveBeenCalled();
50
- expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
63
+ expect(tx.session.deleteMany).not.toHaveBeenCalled();
51
64
  });
52
65
 
53
66
  it('activating an unverified user also approves the email; no sessions are touched', async () => {
54
67
  vi.mocked(adminRepository.findUserById).mockResolvedValue(adminUser({ emailVerifiedAt: null, isActive: false }));
55
- await adminService.toggleUserStatus(USER_ID, true, ADMIN_ID);
56
- expect(adminRepository.updateUserStatus).toHaveBeenCalledWith(USER_ID, true, true);
57
- expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
68
+ await adminService.toggleUserStatus(USER_ID, true, actor);
69
+ expect(adminRepository.updateUserStatus).toHaveBeenCalledWith(tx, USER_ID, true, true);
70
+ expect(tx.session.deleteMany).not.toHaveBeenCalled();
58
71
  });
59
72
 
60
73
  it('banning an unknown or deleted user answers 404', async () => {
61
74
  vi.mocked(adminRepository.findUserById).mockResolvedValue(null);
62
- await expect(adminService.toggleUserStatus(USER_ID, false, ADMIN_ID)).rejects.toMatchObject({ statusCode: 404 });
75
+ await expect(adminService.toggleUserStatus(USER_ID, false, actor)).rejects.toMatchObject({ statusCode: 404 });
63
76
  });
64
77
  });
65
78
 
66
79
  describe('role changes', () => {
67
80
  it('an admin cannot change their own role', async () => {
68
- await expect(adminService.changeUserRole(ADMIN_ID, 'USER', ADMIN_ID)).rejects.toMatchObject({ statusCode: 403 });
81
+ await expect(adminService.changeUserRole(ADMIN_ID, 'USER', actor)).rejects.toMatchObject({ statusCode: 403 });
69
82
  expect(adminRepository.updateUserRole).not.toHaveBeenCalled();
70
83
  });
71
84
 
72
85
  it("demoting another admin ends that admin's sessions", async () => {
73
86
  vi.mocked(adminRepository.findUserById).mockResolvedValue(adminUser({ id: USER_ID, role: 'ADMIN' }));
74
- await adminService.changeUserRole(USER_ID, 'USER', ADMIN_ID);
75
- expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(USER_ID);
76
- expect(deleteRefreshTokensByUserId).toHaveBeenCalledWith(USER_ID);
87
+ await adminService.changeUserRole(USER_ID, 'USER', actor);
88
+ expect(tx.session.deleteMany).toHaveBeenCalledWith({ where: { userId: USER_ID } });
89
+ expect(tx.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { userId: USER_ID } });
77
90
  });
78
91
 
79
92
  it('promoting a user keeps their sessions (the role is re-read on every request)', async () => {
80
- await adminService.changeUserRole(USER_ID, 'ADMIN', ADMIN_ID);
81
- expect(adminRepository.updateUserRole).toHaveBeenCalledWith(USER_ID, 'ADMIN');
82
- expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
93
+ await adminService.changeUserRole(USER_ID, 'ADMIN', actor);
94
+ expect(adminRepository.updateUserRole).toHaveBeenCalledWith(tx, USER_ID, 'ADMIN');
95
+ expect(tx.session.deleteMany).not.toHaveBeenCalled();
96
+ });
97
+
98
+ it('refuses a role change if the actor was demoted before the write', async () => {
99
+ tx.user.findUnique.mockResolvedValue(adminUser({ id: ADMIN_ID, role: 'USER' }));
100
+ await expect(adminService.changeUserRole(USER_ID, 'ADMIN', actor)).rejects.toMatchObject({ statusCode: 403 });
101
+ expect(adminRepository.updateUserRole).not.toHaveBeenCalled();
102
+ });
103
+
104
+ it('refuses a role change from a revoked session', async () => {
105
+ tx.session.findFirst.mockResolvedValue(null);
106
+ await expect(adminService.changeUserRole(USER_ID, 'ADMIN', actor)).rejects.toMatchObject({ statusCode: 401 });
107
+ expect(adminRepository.updateUserRole).not.toHaveBeenCalled();
108
+ });
109
+
110
+ it('returns 503 after exhausting three write conflict attempts', async () => {
111
+ vi.mocked(prisma.$transaction).mockRejectedValue(Object.assign(new Error('conflict'), { code: 'P2034' }));
112
+ await expect(adminService.changeUserRole(USER_ID, 'ADMIN', actor)).rejects.toMatchObject({ statusCode: 503 });
113
+ expect(prisma.$transaction).toHaveBeenCalledTimes(3);
114
+ });
115
+
116
+ it('rechecks target state after a transient write conflict', async () => {
117
+ vi.mocked(adminRepository.updateUserRole).mockRejectedValueOnce(Object.assign(new Error('conflict'), { code: 'P2034' }));
118
+ vi.mocked(adminRepository.findUserById).mockResolvedValueOnce(adminUser()).mockResolvedValueOnce(null);
119
+ await expect(adminService.changeUserRole(USER_ID, 'ADMIN', actor)).rejects.toMatchObject({ statusCode: 404 });
120
+ expect(prisma.$transaction).toHaveBeenCalledTimes(2);
83
121
  });
84
122
  });
85
123
 
86
124
  describe('force-expire a session', () => {
87
- it('deletes its refresh tokens, then the session', async () => {
88
- vi.mocked(adminRepository.getSessionById).mockResolvedValue({ id: 's1', userId: USER_ID } as never);
89
- await adminService.forceExpireSession('s1');
90
- const tokensAt = vi.mocked(adminRepository.deleteRefreshTokensBySessionId).mock.invocationCallOrder[0];
91
- const sessionAt = vi.mocked(adminRepository.deleteSession).mock.invocationCallOrder[0];
92
- expect(tokensAt).toBeLessThan(sessionAt);
125
+ it('answers 404 when no live session was removed', async () => {
126
+ vi.mocked(adminRepository.deleteLiveSession).mockResolvedValue(false);
127
+ await expect(adminService.forceExpireSession('expired', actor)).rejects.toMatchObject({ statusCode: 404 });
93
128
  });
94
129
 
95
- it('answers 404 for an unknown session', async () => {
96
- vi.mocked(adminRepository.getSessionById).mockResolvedValue(null);
97
- await expect(adminService.forceExpireSession('missing')).rejects.toMatchObject({ statusCode: 404 });
98
- expect(adminRepository.deleteSession).not.toHaveBeenCalled();
130
+ it('reports success when the selected session was removed', async () => {
131
+ vi.mocked(adminRepository.deleteLiveSession).mockResolvedValue(true);
132
+ await expect(adminService.forceExpireSession('s1', actor)).resolves.toBeUndefined();
133
+ expect(adminRepository.deleteLiveSession).toHaveBeenCalledWith(tx, 's1');
99
134
  });
100
135
  });
101
136
 
@@ -115,19 +150,27 @@ describe('deleted accounts and restore', () => {
115
150
 
116
151
  it('restores a deleted account and returns it', async () => {
117
152
  vi.mocked(adminRepository.restoreUser).mockResolvedValue(true);
118
- await expect(adminService.restoreUser(USER_ID)).resolves.toMatchObject({ id: USER_ID, isActive: true });
153
+ await expect(adminService.restoreUser(USER_ID, actor)).resolves.toMatchObject({ id: USER_ID, isActive: true });
119
154
  });
120
155
 
121
156
  it('answers 409 USER_NOT_DELETED for an account that is not deleted', async () => {
122
157
  vi.mocked(adminRepository.restoreUser).mockResolvedValue(false);
123
- vi.mocked(adminRepository.userExists).mockResolvedValue(true);
124
- await expect(adminService.restoreUser(USER_ID)).rejects.toMatchObject({ statusCode: 409, code: 'USER_NOT_DELETED' });
158
+ vi.mocked(adminRepository.getPurgeState).mockResolvedValue({ purgeStartedAt: null });
159
+ await expect(adminService.restoreUser(USER_ID, actor)).rejects.toMatchObject({ statusCode: 409, code: 'USER_NOT_DELETED' });
125
160
  });
126
161
 
127
162
  it('answers 404 USER_NOT_FOUND when there is no such account (or it was purged)', async () => {
128
163
  vi.mocked(adminRepository.restoreUser).mockResolvedValue(false);
129
- vi.mocked(adminRepository.userExists).mockResolvedValue(false);
130
- await expect(adminService.restoreUser(USER_ID)).rejects.toMatchObject({ statusCode: 404, code: 'USER_NOT_FOUND' });
164
+ vi.mocked(adminRepository.getPurgeState).mockResolvedValue(null);
165
+ await expect(adminService.restoreUser(USER_ID, actor)).rejects.toMatchObject({ statusCode: 404, code: 'USER_NOT_FOUND' });
166
+ });
167
+
168
+ it('answers 409 when permanent deletion has started', async () => {
169
+ vi.mocked(adminRepository.restoreUser).mockResolvedValue(false);
170
+ vi.mocked(adminRepository.getPurgeState).mockResolvedValue({ purgeStartedAt: new Date() });
171
+ await expect(adminService.restoreUser(USER_ID, actor)).rejects.toMatchObject({
172
+ statusCode: 409, code: 'USER_PURGE_IN_PROGRESS',
173
+ });
131
174
  });
132
175
  });
133
176
 
@@ -138,14 +181,14 @@ describe('promoteToAdmin (make-admin)', () => {
138
181
  it('promotes an existing account, looked up by its lower-cased email, and keeps its verification date', async () => {
139
182
  vi.mocked(adminRepository.findAccountStateByEmail).mockResolvedValue(state());
140
183
  await expect(adminService.promoteToAdmin(' Owner@Example.TEST ')).resolves.toBe('promoted');
141
- expect(adminRepository.findAccountStateByEmail).toHaveBeenCalledWith('owner@example.test');
142
- expect(adminRepository.promoteToAdmin).toHaveBeenCalledWith(USER_ID, new Date('2026-01-01'));
184
+ expect(adminRepository.findAccountStateByEmail).toHaveBeenCalledWith(tx, 'owner@example.test');
185
+ expect(adminRepository.promoteToAdmin).toHaveBeenCalledWith(tx, USER_ID, new Date('2026-01-01'));
143
186
  });
144
187
 
145
188
  it('marks an unverified account verified when promoting it', async () => {
146
189
  vi.mocked(adminRepository.findAccountStateByEmail).mockResolvedValue(state({ emailVerifiedAt: null }));
147
190
  await adminService.promoteToAdmin('owner@example.test');
148
- expect(vi.mocked(adminRepository.promoteToAdmin).mock.calls[0]?.[1]).toBeInstanceOf(Date);
191
+ expect(vi.mocked(adminRepository.promoteToAdmin).mock.calls[0]?.[2]).toBeInstanceOf(Date);
149
192
  });
150
193
 
151
194
  it.each([