create-tigra 3.3.0 → 4.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 (207) hide show
  1. package/CHANGELOG.md +151 -0
  2. package/README.md +264 -56
  3. package/bin/create-tigra.js +497 -472
  4. package/lib/patchers/email-verification.patcher.js +72 -10
  5. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  6. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  7. package/modules/email-verification/server/verification.controller.ts +3 -1
  8. package/modules/email-verification/server/verification.service.ts +44 -13
  9. package/package.json +5 -3
  10. package/template/.github/dependabot.yml +47 -0
  11. package/template/.github/workflows/audit.yml +36 -0
  12. package/template/.github/workflows/ci.yml +79 -0
  13. package/template/AGENTS.md +18 -9
  14. package/template/README.md +79 -0
  15. package/template/client/.dockerignore +1 -0
  16. package/template/client/.env.example.production +13 -2
  17. package/template/client/AGENTS.md +13 -5
  18. package/template/client/Dockerfile +186 -14
  19. package/template/client/README.md +92 -21
  20. package/template/client/next.config.ts +1 -1
  21. package/template/client/package-lock.json +15983 -14181
  22. package/template/client/package.json +56 -48
  23. package/template/client/scripts/check-sharp.mjs +53 -0
  24. package/template/client/scripts/next-dev.cjs +5 -1
  25. package/template/client/src/__tests__/proxy.test.ts +92 -0
  26. package/template/client/src/app/healthz/route.ts +16 -0
  27. package/template/client/src/app/layout.tsx +9 -3
  28. package/template/client/src/app/page.tsx +2 -2
  29. package/template/client/src/app/providers.tsx +23 -4
  30. package/template/client/src/components/layout/Header.tsx +7 -3
  31. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  32. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  33. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  34. package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
  35. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  36. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  37. package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
  38. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  39. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  40. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  41. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  42. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  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 +1 -1
  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 +81 -0
  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/session-marker.ts +24 -0
  59. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  60. package/template/client/src/store/__tests__/store.test.ts +44 -0
  61. package/template/client/src/store/index.ts +26 -8
  62. package/template/client/vitest.config.mts +48 -0
  63. package/template/server/.env.example +280 -270
  64. package/template/server/.env.example.production +283 -242
  65. package/template/server/AGENTS.md +13 -4
  66. package/template/server/Dockerfile +176 -14
  67. package/template/server/README.md +108 -0
  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 +66 -4
  71. package/template/server/docs/rate-limits.md +153 -0
  72. package/template/server/docs/testing.md +81 -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 +0 -3
  79. package/template/server/scripts/check-heic.mjs +40 -0
  80. package/template/server/scripts/check-sharp.mjs +53 -0
  81. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  82. package/template/server/src/app.ts +248 -346
  83. package/template/server/src/config/__tests__/env.test.ts +219 -0
  84. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  85. package/template/server/src/config/env.ts +326 -182
  86. package/template/server/src/config/rate-limit.config.ts +157 -106
  87. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  88. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  89. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  90. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  91. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  92. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  93. package/template/server/src/jobs/index.ts +12 -2
  94. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  95. package/template/server/src/jobs/schedule.ts +50 -0
  96. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  97. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  98. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  99. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  100. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  101. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  102. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  103. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  104. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  105. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  106. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  107. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  108. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  109. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  110. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  111. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  112. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  113. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  114. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  115. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  116. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  117. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  118. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  119. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  120. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  121. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  122. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  123. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  124. package/template/server/src/libs/auth.ts +39 -10
  125. package/template/server/src/libs/client-ip.ts +158 -77
  126. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  127. package/template/server/src/libs/cookies.ts +53 -14
  128. package/template/server/src/libs/email-quota.ts +74 -0
  129. package/template/server/src/libs/email.ts +46 -9
  130. package/template/server/src/libs/error-handler.ts +111 -0
  131. package/template/server/src/libs/health-routes.ts +53 -0
  132. package/template/server/src/libs/http.ts +139 -47
  133. package/template/server/src/libs/ip-address.ts +37 -0
  134. package/template/server/src/libs/ip-block.ts +284 -221
  135. package/template/server/src/libs/logger.ts +41 -12
  136. package/template/server/src/libs/monitoring.ts +127 -41
  137. package/template/server/src/libs/observability/sentry.ts +1 -1
  138. package/template/server/src/libs/origin-check.ts +9 -7
  139. package/template/server/src/libs/prisma.ts +47 -4
  140. package/template/server/src/libs/query-counter.ts +71 -59
  141. package/template/server/src/libs/rate-limiting.ts +110 -0
  142. package/template/server/src/libs/redis-required.ts +28 -0
  143. package/template/server/src/libs/redis.ts +27 -1
  144. package/template/server/src/libs/request-id.ts +18 -0
  145. package/template/server/src/libs/requestLogger.ts +112 -17
  146. package/template/server/src/libs/safe-http.ts +101 -0
  147. package/template/server/src/libs/shutdown.ts +87 -0
  148. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  149. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  150. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  151. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  152. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  153. package/template/server/src/libs/storage/file-validator.ts +48 -46
  154. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  155. package/template/server/src/libs/token-hash.ts +18 -0
  156. package/template/server/src/libs/url-safety.ts +127 -121
  157. package/template/server/src/libs/validation-errors.ts +86 -0
  158. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  159. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  160. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  161. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  162. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  163. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  164. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  165. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  166. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  167. package/template/server/src/modules/admin/admin.service.ts +66 -4
  168. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  170. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  171. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  172. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  173. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  174. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  175. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  176. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  177. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  178. package/template/server/src/modules/auth/auth.service.ts +167 -96
  179. package/template/server/src/modules/auth/session.repo.ts +12 -0
  180. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  181. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  182. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  183. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  184. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  185. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  186. package/template/server/src/modules/users/users.controller.ts +9 -38
  187. package/template/server/src/modules/users/users.repo.ts +23 -7
  188. package/template/server/src/modules/users/users.routes.ts +3 -22
  189. package/template/server/src/modules/users/users.schemas.ts +15 -9
  190. package/template/server/src/modules/users/users.service.ts +105 -93
  191. package/template/server/src/scripts/make-admin.ts +48 -0
  192. package/template/server/src/server.ts +48 -26
  193. package/template/server/src/shared/errors/AppError.ts +27 -1
  194. package/template/server/src/shared/errors/errors.ts +42 -5
  195. package/template/server/src/shared/responses/successResponse.ts +22 -3
  196. package/template/server/src/shared/types/index.ts +7 -0
  197. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  198. package/template/server/src/test/integration-helpers.ts +343 -0
  199. package/template/server/src/test/integration-services.ts +74 -0
  200. package/template/server/src/test/integration.global-setup.ts +144 -0
  201. package/template/server/src/test/integration.setup.ts +35 -158
  202. package/template/server/src/test/setup.ts +3 -10
  203. package/template/server/tsconfig.build.json +1 -1
  204. package/template/server/tsconfig.json +1 -0
  205. package/template/server/vitest.config.ts +17 -4
  206. package/template/server/vitest.integration.config.ts +18 -13
  207. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -13,22 +13,72 @@
13
13
  * root and is reachable ONLY through the auth-gated, owner-scoped streaming
14
14
  * route GET /api/v1/files/:filename (see src/modules/files/).
15
15
  *
16
- * The public avatar URL shape is UNCHANGED — `/uploads/users/{id}/avatar/x.webp`
17
- * — because the static mount serves UPLOAD_PUBLIC_DIR at prefix `/uploads/`, so
18
- * the file just moves one level down on disk (under public/) with no URL churn.
16
+ * Public avatar URLs look like `/uploads/users/{id}/avatar/avatar-<16 hex>.webp`:
17
+ * the static mount serves UPLOAD_PUBLIC_DIR at prefix `/uploads/`.
18
+ *
19
+ * ── Public files never change under the same name ──────────────────────────
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.
19
25
  */
20
26
 
27
+ import { randomBytes } from 'node:crypto';
28
+ import { existsSync, statSync } from 'node:fs';
21
29
  import fs from 'fs/promises';
22
30
  import path from 'path';
23
31
  import { env } from '@config/env.js';
24
32
  import { logger } from '@libs/logger.js';
25
33
  import { InternalError } from '@shared/errors/errors.js';
26
- import { generateAvatarFilename } from './filename-sanitizer.js';
34
+
35
+ /** How uploadDirsOnContainerDisk looks at the disk (injectable for tests). */
36
+ export interface DiskProbe {
37
+ exists(p: string): boolean;
38
+ /** The filesystem device id of a path (fs.stat().dev). */
39
+ device(p: string): number;
40
+ }
41
+
42
+ const realDisk: DiskProbe = {
43
+ exists: (p) => existsSync(p),
44
+ device: (p) => statSync(p).dev,
45
+ };
46
+
47
+ /**
48
+ * Upload folders that sit on the container's own disk and would therefore be
49
+ * lost on the next deploy (Coolify starts a fresh container each time).
50
+ *
51
+ * Only in production inside a Docker container (/.dockerenv exists): there the
52
+ * container's writable layer is "/", and a folder on the same device as "/" is
53
+ * not on a mounted volume. Never in dev or test, never outside a container (a
54
+ * plain server's disk is persistent), and a folder that cannot be checked is
55
+ * left out rather than guessed. The caller only warns: a project that stores
56
+ * no files must still start.
57
+ */
58
+ export function uploadDirsOnContainerDisk(
59
+ dirs: readonly string[],
60
+ nodeEnv: string,
61
+ disk: DiskProbe = realDisk,
62
+ ): string[] {
63
+ if (nodeEnv !== 'production' || !disk.exists('/.dockerenv')) return [];
64
+ try {
65
+ const rootDevice = disk.device('/');
66
+ return dirs.filter((dir) => {
67
+ try {
68
+ return disk.device(dir) === rootDevice;
69
+ } catch {
70
+ return false;
71
+ }
72
+ });
73
+ } catch {
74
+ return [];
75
+ }
76
+ }
27
77
 
28
78
  /**
29
79
  * File Storage Service
30
80
  *
31
- * Manages local file storage with per-user directories and SEO-friendly naming.
81
+ * Manages local file storage with per-user directories.
32
82
  * All user media lives under {tier}/users/{userId}/ for easy per-user cleanup.
33
83
  */
34
84
  class FileStorageService {
@@ -82,62 +132,25 @@ class FileStorageService {
82
132
  }
83
133
 
84
134
  /**
85
- * Saves an avatar image to user-specific directory
135
+ * Writes a NEW avatar file under a fresh random name and returns its URL.
86
136
  *
87
- * Process:
88
- * 1. Create user avatar directory if it doesn't exist
89
- * 2. Generate SEO-friendly filename
90
- * 3. Save buffer to file (overwrites existing avatar)
91
- * 4. Return filename and public URL
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.
92
141
  *
93
142
  * @param userId - User's unique ID
94
- * @param buffer - Optimized image buffer
95
- * @param firstName - User's first name (for SEO filename)
96
- * @param lastName - User's last name (for SEO filename)
97
- * @returns Filename and URL of saved avatar
98
- *
99
- * @example
100
- * ```typescript
101
- * const { filename, url } = await fileStorageService.saveAvatar(
102
- * userId,
103
- * imageBuffer,
104
- * 'John',
105
- * 'Doe'
106
- * );
107
- * // filename: "john-doe-avatar.webp"
108
- * // url: "/uploads/users/{userId}/avatar/john-doe-avatar.webp"
109
- * ```
143
+ * @param buffer - Optimized image buffer (always WebP)
144
+ * @returns Filename and public URL, e.g. /uploads/users/{userId}/avatar/avatar-3f9c0a1b2c3d4e5f.webp
110
145
  */
111
- async saveAvatar(
112
- userId: string,
113
- buffer: Buffer,
114
- firstName: string,
115
- lastName: string
116
- ): Promise<{ filename: string; url: string }> {
146
+ async saveAvatar(userId: string, buffer: Buffer): Promise<{ filename: string; url: string }> {
117
147
  try {
118
- // Ensure user's avatar directory exists
119
148
  const avatarDir = this.getUserAvatarDir(userId);
120
149
  await this.ensureDirectoryExists(avatarDir);
121
150
 
122
- // Generate SEO-friendly filename
123
- const filename = generateAvatarFilename(firstName, lastName, 'webp');
124
- const filePath = path.join(avatarDir, filename);
125
-
126
- // Write file to disk (overwrites existing)
127
- await fs.writeFile(filePath, buffer);
151
+ const filename = `avatar-${randomBytes(8).toString('hex')}.webp`;
152
+ await fs.writeFile(path.join(avatarDir, filename), buffer);
128
153
 
129
- // Remove any previous avatar files. The filename comes from the user's
130
- // name, so after a name change the old file would otherwise stay publicly
131
- // reachable at its old URL (possibly with metadata from before EXIF
132
- // stripping). New file is written first, so there is never a moment with
133
- // no avatar.
134
- for (const entry of await fs.readdir(avatarDir)) {
135
- if (entry !== filename) {
136
- await fs.rm(path.join(avatarDir, entry), { force: true, recursive: true });
137
- }
138
- }
139
-
140
- // Generate public URL
141
154
  const url = `/uploads/users/${userId}/avatar/${filename}`;
142
155
 
143
156
  logger.info({
@@ -218,25 +231,21 @@ class FileStorageService {
218
231
  }
219
232
 
220
233
  /**
221
- * Gets the full file system path for an avatar
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.
222
238
  *
223
- * @param userId - User's unique ID
224
- * @param filename - Avatar filename
225
- * @returns Absolute file path
239
+ * Only the basename is used, so whatever a stored URL says, the path stays
240
+ * inside this user's avatar folder.
226
241
  */
227
- getAvatarPath(userId: string, filename: string): string {
228
- return path.join(this.getUserAvatarDir(userId), filename);
229
- }
230
-
231
- /**
232
- * Gets the public URL for an avatar
233
- *
234
- * @param userId - User's unique ID
235
- * @param filename - Avatar filename
236
- * @returns Public URL path
237
- */
238
- getAvatarUrl(userId: string, filename: string): string {
239
- return `/uploads/users/${userId}/avatar/${filename}`;
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
+ }
240
249
  }
241
250
 
242
251
  /**
@@ -321,21 +330,6 @@ class FileStorageService {
321
330
  return path.join(this.getUserPrivateDir(userId), safeName);
322
331
  }
323
332
 
324
- /**
325
- * Checks if a file exists
326
- *
327
- * @param filePath - Full file path
328
- * @returns True if file exists
329
- */
330
- async fileExists(filePath: string): Promise<boolean> {
331
- try {
332
- await fs.access(filePath);
333
- return true;
334
- } catch {
335
- return false;
336
- }
337
- }
338
-
339
333
  /**
340
334
  * Ensures a directory exists, creates it if not
341
335
  *
@@ -391,6 +385,22 @@ class FileStorageService {
391
385
  throw new InternalError('Failed to initialize file storage', 'STORAGE_INIT_FAILED');
392
386
  }
393
387
  }
388
+
389
+ /**
390
+ * Warns (once per tier, at boot) when an upload tier is not on a mounted
391
+ * volume in a production container, so uploads would vanish on the next
392
+ * deploy. The deploy step it points to is in the README and
393
+ * .env.example.production. Never stops the server.
394
+ */
395
+ warnIfUploadsNotPersistent(): void {
396
+ for (const dir of uploadDirsOnContainerDisk([this.publicDir, this.privateDir], env.NODE_ENV)) {
397
+ logger.warn(
398
+ { dir },
399
+ `[STORAGE] ${dir} is not on a mounted volume: uploaded files will be lost on the next deploy. ` +
400
+ 'In Coolify add a volume mount at /app/uploads (Storages → Add Volume Mount).',
401
+ );
402
+ }
403
+ }
394
404
  }
395
405
 
396
406
  // Export singleton instance
@@ -1,81 +1,83 @@
1
1
  /**
2
2
  * File Upload Validator
3
3
  *
4
- * Validates uploaded files for security and compliance with upload constraints.
4
+ * Size and count limits for uploads. Which image formats are accepted is NOT
5
+ * decided here: the browser-sent type and filename are not trusted, and are
6
+ * often wrong for real photos (a browser that does not know .heic sends
7
+ * application/octet-stream). The image's own bytes decide, in
8
+ * image-optimizer.service.ts, and the output is always a re-encoded WebP.
5
9
  */
6
10
 
7
11
  import type { MultipartFile } from '@fastify/multipart';
12
+ import { AppError } from '@shared/errors/AppError.js';
8
13
  import { ValidationError } from '@shared/errors/errors.js';
9
14
  import { env } from '@config/env.js';
10
- import path from 'path';
11
15
 
12
16
  /**
13
17
  * File upload constants and constraints
14
18
  */
15
19
  export const FILE_UPLOAD_CONSTANTS = {
16
20
  MAX_FILE_SIZE: env.MAX_FILE_SIZE_MB * 1024 * 1024, // ENV-configurable (default 10MB)
17
- ALLOWED_MIME_TYPES: ['image/jpeg', 'image/png', 'image/webp', 'image/heic', 'image/heif'] as const,
18
- ALLOWED_EXTENSIONS: ['.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif'] as const,
19
21
  AVATAR_MAX_DIMENSION: 512, // pixels
20
22
  } as const;
21
23
 
22
24
  /**
23
- * Validates an uploaded image file
25
+ * Limits for the non-file parts of a multipart upload (passed to
26
+ * @fastify/multipart in app.ts, next to the file size and count).
24
27
  *
25
- * Checks:
26
- * - File size within limits
27
- * - MIME type is allowed
28
- * - File extension is allowed (prevents disguised files)
29
- * - File is not executable
28
+ * Form fields that arrive BEFORE the file are kept in memory while the parser
29
+ * looks for the file. The library defaults (1 MB per field, 1,000 parts) let one
30
+ * request make the server hold about 1 GB, and any signed-in user (registration
31
+ * is free) can send that to the avatar upload. Proven live: 300 fields of 1 MB
32
+ * grew the server by 429 MB. These caps bound it to about 2 MB:
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.
35
+ * Raise them only for a route that really sends many or large fields.
36
+ */
37
+ export const MULTIPART_LIMITS = {
38
+ fields: 20,
39
+ fieldSize: 100 * 1024, // bytes per field
40
+ parts: 25, // fields + files, a backstop behind the two limits above
41
+ } as const;
42
+
43
+ /**
44
+ * Checks that an upload carries a file.
30
45
  *
31
- * @param file - Fastify multipart file object
32
- * @throws ValidationError if file is invalid
46
+ * The browser-sent MIME type and filename are deliberately ignored: they are
47
+ * the client's claim, not the content. imageOptimizerService.optimizeAvatar
48
+ * judges the real format from the bytes and re-encodes the image, so a file
49
+ * named photo.exe that is really a PNG becomes a plain WebP, and a text file
50
+ * named photo.jpg is refused.
33
51
  *
34
- * @example
35
- * ```typescript
36
- * const file = await request.file();
37
- * validateImageFile(file); // Throws if invalid
38
- * ```
52
+ * @param file - Fastify multipart file object
53
+ * @throws ValidationError (FILE_REQUIRED) when no file was sent
39
54
  */
40
- export function validateImageFile(file: MultipartFile): void {
41
- // Validate file exists
55
+ export function validateImageFile(file: MultipartFile | undefined): void {
42
56
  if (!file) {
43
57
  throw new ValidationError('No file was uploaded', 'FILE_REQUIRED');
44
58
  }
45
-
46
- // Validate MIME type
47
- const mimeType = file.mimetype;
48
- if (!(FILE_UPLOAD_CONSTANTS.ALLOWED_MIME_TYPES as readonly string[]).includes(mimeType)) {
49
- throw new ValidationError(
50
- `Invalid file type. Allowed types: ${FILE_UPLOAD_CONSTANTS.ALLOWED_MIME_TYPES.join(', ')}`,
51
- 'INVALID_FILE_TYPE'
52
- );
53
- }
54
-
55
- // Validate file extension (prevents MIME type spoofing)
56
- const extension = path.extname(file.filename).toLowerCase();
57
- if (!(FILE_UPLOAD_CONSTANTS.ALLOWED_EXTENSIONS as readonly string[]).includes(extension)) {
58
- throw new ValidationError(
59
- `Invalid file extension. Allowed extensions: ${FILE_UPLOAD_CONSTANTS.ALLOWED_EXTENSIONS.join(', ')}`,
60
- 'INVALID_FILE_EXTENSION'
61
- );
62
- }
63
-
64
- // Prevent executable files (extra security layer)
65
- const dangerousExtensions = ['.exe', '.sh', '.bat', '.cmd', '.com', '.pif', '.scr', '.vbs', '.js'];
66
- const lowerFilename = file.filename.toLowerCase();
67
- if (dangerousExtensions.some((ext) => lowerFilename.endsWith(ext))) {
68
- throw new ValidationError('Executable files are not allowed', 'DANGEROUS_FILE');
69
- }
70
59
  }
71
60
 
72
61
  /**
73
62
  * Validates file buffer size
74
63
  *
64
+ * `truncated` is the multipart file's own flag (`file.file.truncated`), and it
65
+ * must be passed. @fastify/multipart cuts a file at MAX_FILE_SIZE, but its
66
+ * toBuffer() only throws (413 FILE_TOO_LARGE) when it notices the cut while
67
+ * still reading. When the cut lands after the last chunk, it returns the first
68
+ * MAX_FILE_SIZE bytes as if the file were complete. Proven live: an 11 MB file
69
+ * got through cut in 3 of 5 tries, and a cut 10.7 MB JPEG then failed as a 500.
70
+ *
75
71
  * @param buffer - File buffer
76
- * @throws ValidationError if buffer exceeds max size
72
+ * @param truncated - Whether the parser cut the file at the size limit
73
+ * @throws AppError 413 FILE_TOO_LARGE if the file was cut at the limit
74
+ * @throws ValidationError if the buffer is empty or exceeds max size
77
75
  */
78
- export function validateFileSize(buffer: Buffer): void {
76
+ export function validateFileSize(buffer: Buffer, truncated: boolean): void {
77
+ if (truncated) {
78
+ throw new AppError('FILE_TOO_LARGE', 'File size exceeds the maximum allowed limit', 413);
79
+ }
80
+
79
81
  if (buffer.length === 0) {
80
82
  throw new ValidationError('Uploaded file is empty', 'FILE_EMPTY');
81
83
  }
@@ -14,6 +14,12 @@
14
14
  * the compressed bytes, so we also cap the decoded pixel count BEFORE
15
15
  * decoding, accept only real JPEG/PNG/WebP/HEIF content (judged from the
16
16
  * bytes, not the client's filename or MIME type), and time out slow work.
17
+ * - HEIC (iPhone photos) is decoded by libheif's libde265 plugin, which the
18
+ * server Docker image installs and proves at build time
19
+ * (scripts/check-heic.mjs). sharp's prebuilt binaries on developer machines
20
+ * have no HEVC decoder: there a HEIC upload answers 422
21
+ * UNSUPPORTED_IMAGE_FORMAT, never a 500. 'heif' also covers AVIF, which every
22
+ * build decodes.
17
23
  */
18
24
 
19
25
  import sharp from 'sharp';
@@ -28,9 +34,11 @@ import { logger } from '@libs/logger.js';
28
34
  */
29
35
  export const MAX_INPUT_PIXELS = 50_000_000;
30
36
 
31
- /** Formats sharp detects from the file's bytes that we accept for avatars. */
37
+ /** Formats sharp detects from the file's bytes that we accept for avatars ('heif' = HEIC and AVIF). */
32
38
  export const ALLOWED_INPUT_FORMATS = ['jpeg', 'png', 'webp', 'heif'] as const;
33
39
 
40
+ const UNSUPPORTED_FORMAT_MESSAGE = 'Image format is not supported. Use JPEG, PNG, WebP or HEIC.';
41
+
34
42
  /** Hard stop for a single image's processing time. */
35
43
  const PROCESSING_TIMEOUT_SECONDS = 10;
36
44
 
@@ -66,10 +74,7 @@ class ImageOptimizerService {
66
74
  throw new ValidationError('Unable to read image dimensions', 'INVALID_IMAGE');
67
75
  }
68
76
  if (!metadata.format || !(ALLOWED_INPUT_FORMATS as readonly string[]).includes(metadata.format)) {
69
- throw new ValidationError(
70
- 'Image format is not supported. Use JPEG, PNG or WebP.',
71
- 'UNSUPPORTED_IMAGE_FORMAT',
72
- );
77
+ throw new ValidationError(UNSUPPORTED_FORMAT_MESSAGE, 'UNSUPPORTED_IMAGE_FORMAT');
73
78
  }
74
79
  if (metadata.width * metadata.height > MAX_INPUT_PIXELS) {
75
80
  throw new ValidationError('Image dimensions are too large', 'IMAGE_TOO_LARGE');
@@ -117,6 +122,12 @@ class ImageOptimizerService {
117
122
  if (message.includes('timeout')) {
118
123
  throw new ValidationError('Image is too complex to process', 'IMAGE_TOO_COMPLEX');
119
124
  }
125
+ // A real HEIC on a build without the HEVC decoder (sharp's prebuilt
126
+ // binaries): the header reads fine, decoding says the compression
127
+ // "has not been built in". The format, not the file, is the problem.
128
+ if (message.includes('has not been built in')) {
129
+ throw new ValidationError(UNSUPPORTED_FORMAT_MESSAGE, 'UNSUPPORTED_IMAGE_FORMAT');
130
+ }
120
131
  if (
121
132
  message.includes('unsupported image format') ||
122
133
  message.includes('input file is missing') ||
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Fingerprint of a bearer token, the only form a token is stored in.
3
+ *
4
+ * Refresh tokens (MySQL) and password-reset / email-verification tokens
5
+ * (Redis) are stored as their SHA-256 here; the raw token exists only in the
6
+ * user's cookie or email link. So anyone who can merely READ the database or
7
+ * Redis (a stolen backup, a read-only reporting account, an SQL injection
8
+ * elsewhere) cannot sign in as anybody with what they read.
9
+ *
10
+ * A fast hash is enough: these tokens are long random values (122-bit UUIDs,
11
+ * 256-bit hex), not passwords, so there is nothing to brute-force. Lookup is
12
+ * by equality of the fingerprint (an indexed column / a Redis key).
13
+ */
14
+ import { createHash } from 'node:crypto';
15
+
16
+ export function hashToken(raw: string): string {
17
+ return createHash('sha256').update(raw, 'utf8').digest('hex');
18
+ }