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
@@ -0,0 +1,13 @@
1
+ /**
2
+ * A real HEIC (HEVC-coded HEIF, brand 'heic'): 16x16 solid colour, 467 bytes, no
3
+ * EXIF/XMP. Generated with pillow-heif (libheif 1.23 + x265); it is not a photo.
4
+ * The same bytes are embedded in scripts/check-heic.mjs (the image build check).
5
+ */
6
+ export const TINY_HEIC_BASE64 =
7
+ 'AAAAHGZ0eXBoZWljAAAAAG1pZjFoZWljbWlhZgAAAXxtZXRhAAAAAAAAACFoZGxyAAAAAAAAAABwaWN0AAAAAAAAAAAAAAAAAAAA' +
8
+ 'ACJpbG9jAAAAAERAAAEAAQAAAAABoAABAAAAAAAAADMAAAAjaWluZgAAAAAAAQAAABVpbmZlAgAAAAABAABodmMxAAAAAA5waXRt' +
9
+ 'AAAAAAABAAAA/GlwcnAAAADcaXBjbwAAAHVodmNDAQNwAAAAkAAAAAAAHvAA/P34+AAADwNgAAEAGEABDAH//wNwAAADAJAAAAMA' +
10
+ 'AAMAHroCQGEAAQApQgEBA3AAAAMAkAAAAwAAAwAeoCCBBZbqrprm4CGgwIAAAAyAAAADAIRiAAEABkQBwXPBiQAAABNjb2xybmNs' +
11
+ 'eAABAA0ABoAAAAAUaXNwZQAAAAAAAABAAAAAQAAAAChjbGFwAAAAEAAAAAEAAAAQAAAAAf///9AAAAAC////0AAAAAIAAAAQcGl4' +
12
+ 'aQAAAAADCAgIAAAAGGlwbWEAAAAAAAAAAQABBYECAwWEAAAAO21kYXQAAAAvKAGvEyFkY0D4EPdn/9RdjB6iuj/gbsenOyEdwNIg' +
13
+ 'gJtASJNdUAsWEICHdqVW3Pg=';
@@ -0,0 +1,143 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { crc32, deflateSync } from 'node:zlib';
3
+ import sharp from 'sharp';
4
+ import { imageOptimizerService, MAX_INPUT_PIXELS } from '../image-optimizer.service.js';
5
+ import { validateFileSize, validateImageFile } from '../file-validator.js';
6
+ import { TINY_HEIC_BASE64 } from './fixtures/tiny-heic.js';
7
+ import type { MultipartFile } from '@fastify/multipart';
8
+
9
+ // Avatars are public: the output must carry no metadata (GPS, device), and a
10
+ // small file describing a huge picture must be refused before it is decoded.
11
+
12
+ /**
13
+ * A ~70-byte PNG whose header claims width×height. Its pixel data is truncated:
14
+ * enough for the header to be read, which is exactly where the limit must act.
15
+ */
16
+ function pngHeaderOnly(width: number, height: number): Buffer {
17
+ const chunk = (type: string, data: Buffer): Buffer => {
18
+ const length = Buffer.alloc(4);
19
+ length.writeUInt32BE(data.length);
20
+ const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
21
+ const crc = Buffer.alloc(4);
22
+ crc.writeUInt32BE(crc32(body) >>> 0);
23
+ return Buffer.concat([length, body, crc]);
24
+ };
25
+ const ihdr = Buffer.alloc(13);
26
+ ihdr.writeUInt32BE(width, 0);
27
+ ihdr.writeUInt32BE(height, 4);
28
+ ihdr[8] = 8; // bit depth
29
+ ihdr[9] = 2; // colour type RGB
30
+ return Buffer.concat([
31
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
32
+ chunk('IHDR', ihdr),
33
+ chunk('IDAT', deflateSync(Buffer.alloc(64))),
34
+ chunk('IEND', Buffer.alloc(0)),
35
+ ]);
36
+ }
37
+
38
+ describe('imageOptimizerService.optimizeAvatar', () => {
39
+ it('strips EXIF/GPS/XMP and applies the orientation tag to the pixels', async () => {
40
+ const input = await sharp({ create: { width: 64, height: 32, channels: 3, background: '#808080' } })
41
+ .jpeg()
42
+ .withExif({
43
+ IFD0: { Make: 'DummyCam', Model: 'DummyModel' },
44
+ IFD3: { GPSLatitudeRef: 'N', GPSLatitude: '1/1 2/1 3/1', GPSLongitudeRef: 'E', GPSLongitude: '4/1 5/1 6/1' },
45
+ })
46
+ .withMetadata({ orientation: 6 }) // "rotate 90° clockwise" tag, as phones write it
47
+ .toBuffer();
48
+ expect((await sharp(input).metadata()).exif).toBeDefined();
49
+
50
+ const output = await imageOptimizerService.optimizeAvatar(input);
51
+ const meta = await sharp(output).metadata();
52
+
53
+ expect(meta.format).toBe('webp');
54
+ expect(meta.exif).toBeUndefined();
55
+ expect(meta.xmp).toBeUndefined();
56
+ expect(meta.orientation).toBeUndefined();
57
+ // 64×32 landscape + orientation 6 → stored upright as 32×64
58
+ expect(meta.width).toBe(32);
59
+ expect(meta.height).toBe(64);
60
+ });
61
+
62
+ it('refuses an image above the pixel limit without decoding it', async () => {
63
+ const huge = pngHeaderOnly(16000, 16000); // 256 MP claimed, a few dozen bytes
64
+ expect(16000 * 16000).toBeGreaterThan(MAX_INPUT_PIXELS);
65
+
66
+ const started = Date.now();
67
+ await expect(imageOptimizerService.optimizeAvatar(huge)).rejects.toMatchObject({ code: 'IMAGE_TOO_LARGE' });
68
+ expect(Date.now() - started).toBeLessThan(1000);
69
+ });
70
+
71
+ it('refuses formats outside the allowlist even when named like a PNG', async () => {
72
+ const gif = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#ff0000' } }).gif().toBuffer();
73
+ await expect(imageOptimizerService.optimizeAvatar(gif)).rejects.toMatchObject({
74
+ statusCode: 422,
75
+ code: 'UNSUPPORTED_IMAGE_FORMAT',
76
+ message: 'Image format is not supported. Use JPEG, PNG, WebP or HEIC.',
77
+ });
78
+ });
79
+
80
+ it('refuses bytes that are not an image at all (a text file named photo.jpg)', async () => {
81
+ await expect(imageOptimizerService.optimizeAvatar(Buffer.from('not an image, just text'))).rejects.toMatchObject({
82
+ statusCode: 422,
83
+ });
84
+ });
85
+
86
+ it('accepts AVIF (sharp reports it as heif, and every build decodes it)', async () => {
87
+ const avif = await sharp({ create: { width: 16, height: 16, channels: 3, background: '#20a040' } }).avif().toBuffer();
88
+ const meta = await sharp(await imageOptimizerService.optimizeAvatar(avif)).metadata();
89
+ expect(meta.format).toBe('webp');
90
+ });
91
+
92
+ it('a real HEIC decodes where the build has HEVC (the Docker image), else answers 422, never a 500', async () => {
93
+ const heic = Buffer.from(TINY_HEIC_BASE64, 'base64');
94
+ expect((await sharp(heic).metadata()).compression).toBe('hevc');
95
+ // sharp's prebuilt binaries (developer machines) cannot decode HEVC; the
96
+ // server image can, and scripts/check-heic.mjs proves it at build time.
97
+ const canDecodeHevc = await sharp(heic).resize(1, 1).toBuffer().then(() => true, () => false);
98
+ const result = imageOptimizerService.optimizeAvatar(heic);
99
+ if (canDecodeHevc) {
100
+ expect((await sharp(await result).metadata()).format).toBe('webp');
101
+ } else {
102
+ await expect(result).rejects.toMatchObject({ statusCode: 422, code: 'UNSUPPORTED_IMAGE_FORMAT' });
103
+ }
104
+ });
105
+
106
+ it('accepts a normal photo-sized JPEG', async () => {
107
+ const photo = await sharp({ create: { width: 4000, height: 3000, channels: 3, background: '#336699' } })
108
+ .jpeg()
109
+ .toBuffer();
110
+ const output = await imageOptimizerService.optimizeAvatar(photo);
111
+ const meta = await sharp(output).metadata();
112
+ expect(meta.width).toBe(512);
113
+ expect(meta.height).toBe(384);
114
+ });
115
+ });
116
+
117
+ describe('validateImageFile', () => {
118
+ const file = (mimetype: string, filename: string): MultipartFile => ({ mimetype, filename }) as unknown as MultipartFile;
119
+
120
+ it('ignores the browser-sent type and name: the bytes decide later', () => {
121
+ expect(() => validateImageFile(file('application/octet-stream', 'blob'))).not.toThrow();
122
+ expect(() => validateImageFile(file('image/heic', 'IMG_0001.HEIC'))).not.toThrow();
123
+ expect(() => validateImageFile(file('application/x-msdownload', 'photo.exe'))).not.toThrow();
124
+ });
125
+
126
+ it('refuses an upload without a file', () => {
127
+ expect(() => validateImageFile(undefined)).toThrow(expect.objectContaining({ code: 'FILE_REQUIRED' }));
128
+ });
129
+ });
130
+
131
+ describe('validateFileSize', () => {
132
+ it('refuses a file the parser cut at the size limit with 413 FILE_TOO_LARGE, whatever its length', () => {
133
+ // The cut file is exactly MAX_FILE_SIZE bytes, so a length check alone lets it through.
134
+ expect(() => validateFileSize(Buffer.alloc(16), true)).toThrow(
135
+ expect.objectContaining({ statusCode: 413, code: 'FILE_TOO_LARGE' }),
136
+ );
137
+ });
138
+
139
+ it('accepts a complete file and refuses an empty one', () => {
140
+ expect(() => validateFileSize(Buffer.alloc(16), false)).not.toThrow();
141
+ expect(() => validateFileSize(Buffer.alloc(0), false)).toThrow(expect.objectContaining({ code: 'FILE_EMPTY' }));
142
+ });
143
+ });
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Multipart limits (MULTIPART_LIMITS in ../file-validator.ts) on a small Fastify
3
+ * app wired like src/app.ts: the real @fastify/multipart plugin, the same limits
4
+ * and the global error handler. Form fields sent before the file are buffered,
5
+ * so their number and size must be capped, and going over must be a clear 413,
6
+ * never a 500 and never "your file is too large".
7
+ */
8
+ import Fastify, { type FastifyInstance } from 'fastify';
9
+ import multipart from '@fastify/multipart';
10
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
11
+ import { registerErrorHandler } from '@libs/error-handler.js';
12
+ import { MULTIPART_LIMITS } from '../file-validator.js';
13
+
14
+ const FILE_SIZE = 64 * 1024;
15
+ let app: FastifyInstance;
16
+
17
+ beforeAll(async () => {
18
+ app = Fastify({ logger: false });
19
+ registerErrorHandler(app);
20
+ await app.register(multipart, { limits: { fileSize: FILE_SIZE, files: 1, ...MULTIPART_LIMITS } });
21
+ // Like the avatar upload: take the first file, read it whole.
22
+ app.post('/upload', async (request) => {
23
+ const file = await request.file();
24
+ const bytes = file ? (await file.toBuffer()).length : 0;
25
+ const fields = file ? Object.values(file.fields).filter((f) => f && 'value' in f) : [];
26
+ const longest = Math.max(0, ...fields.map((f) => String((f as { value: unknown }).value).length));
27
+ return { bytes, fields: fields.length, longest };
28
+ });
29
+ await app.ready();
30
+ });
31
+
32
+ afterAll(async () => {
33
+ await app.close();
34
+ });
35
+
36
+ /** A multipart body: `fields` text fields of `fieldBytes` each, then `files` small files. */
37
+ function form(fields: number, fieldBytes = 10, files = 1, fileBytes = 100): { payload: Buffer; headers: Record<string, string> } {
38
+ const boundary = 'limits-test-boundary';
39
+ const parts: Buffer[] = [];
40
+ for (let i = 0; i < fields; i++) {
41
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="f${i}"\r\n\r\n${'a'.repeat(fieldBytes)}\r\n`));
42
+ }
43
+ for (let i = 0; i < files; i++) {
44
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file${i}"; filename="a${i}.bin"\r\nContent-Type: application/octet-stream\r\n\r\n`));
45
+ parts.push(Buffer.alloc(fileBytes, 1), Buffer.from('\r\n'));
46
+ }
47
+ parts.push(Buffer.from(`--${boundary}--\r\n`));
48
+ return { payload: Buffer.concat(parts), headers: { 'content-type': `multipart/form-data; boundary=${boundary}` } };
49
+ }
50
+
51
+ describe('multipart limits', () => {
52
+ it('a normal upload with a few small fields still works', async () => {
53
+ const res = await app.inject({ method: 'POST', url: '/upload', ...form(2) });
54
+ expect(res.statusCode).toBe(200);
55
+ expect(res.json()).toMatchObject({ bytes: 100, fields: 2 });
56
+ });
57
+
58
+ it('more fields than allowed answers 413 MULTIPART_LIMIT, not FILE_TOO_LARGE', async () => {
59
+ const res = await app.inject({ method: 'POST', url: '/upload', ...form(MULTIPART_LIMITS.fields + 1) });
60
+ expect(res.statusCode).toBe(413);
61
+ expect(res.json().error).toEqual({ code: 'MULTIPART_LIMIT', message: 'Too many form fields or files in this upload' });
62
+ });
63
+
64
+ it('too many fields only (no file) answers the same 413', async () => {
65
+ const res = await app.inject({ method: 'POST', url: '/upload', ...form(MULTIPART_LIMITS.fields + 1, 10, 0) });
66
+ expect(res.statusCode).toBe(413);
67
+ expect(res.json().error.code).toBe('MULTIPART_LIMIT');
68
+ });
69
+
70
+ it('a second file is ignored: only the first is read, never a 500', async () => {
71
+ const res = await app.inject({ method: 'POST', url: '/upload', ...form(0, 0, 2) });
72
+ expect(res.statusCode).toBe(200);
73
+ expect(res.json()).toMatchObject({ bytes: 100 });
74
+ });
75
+
76
+ it('a field longer than fieldSize is cut at fieldSize, never kept whole', async () => {
77
+ const res = await app.inject({ method: 'POST', url: '/upload', ...form(1, MULTIPART_LIMITS.fieldSize * 3) });
78
+ expect(res.statusCode).toBe(200);
79
+ expect(res.json().longest).toBe(MULTIPART_LIMITS.fieldSize);
80
+ });
81
+
82
+ it('a file over the size limit still answers 413 FILE_TOO_LARGE', async () => {
83
+ const res = await app.inject({ method: 'POST', url: '/upload', ...form(0, 0, 1, FILE_SIZE + 1) });
84
+ expect(res.statusCode).toBe(413);
85
+ expect(res.json().error.code).toBe('FILE_TOO_LARGE');
86
+ });
87
+
88
+ it('caps fields at about 2 MB in total', () => {
89
+ expect(MULTIPART_LIMITS.fields * MULTIPART_LIMITS.fieldSize).toBeLessThanOrEqual(2 * 1024 * 1024);
90
+ });
91
+ });
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The "uploads will be lost on the next deploy" check (uploadDirsOnContainerDisk
3
+ * in ../file-storage.service.ts) with a fake disk: it flags a folder only in
4
+ * production, only inside a Docker container, and only when the folder is on
5
+ * the container's own disk (same device as "/") rather than a mounted volume.
6
+ */
7
+ import { describe, expect, it } from 'vitest';
8
+ import { type DiskProbe, uploadDirsOnContainerDisk } from '../file-storage.service.js';
9
+
10
+ const DIRS = ['/app/uploads/public', '/app/uploads/private'];
11
+
12
+ /** A fake disk: "/" is device 1; `mounted` folders live on device 2. */
13
+ function disk({ container = true, mounted = [] as string[], broken = [] as string[] } = {}): DiskProbe {
14
+ return {
15
+ exists: (p) => container && p === '/.dockerenv',
16
+ device: (p): number => {
17
+ if (broken.includes(p)) throw new Error('EACCES');
18
+ return mounted.some((m) => p === m || p.startsWith(`${m}/`)) ? 2 : 1;
19
+ },
20
+ };
21
+ }
22
+
23
+ describe('uploadDirsOnContainerDisk', () => {
24
+ it('flags both tiers in a production container without a volume', () => {
25
+ expect(uploadDirsOnContainerDisk(DIRS, 'production', disk())).toEqual(DIRS);
26
+ });
27
+
28
+ it('flags nothing when /app/uploads is a mounted volume', () => {
29
+ expect(uploadDirsOnContainerDisk(DIRS, 'production', disk({ mounted: ['/app/uploads'] }))).toEqual([]);
30
+ });
31
+
32
+ it('flags only the tier that is not on the volume', () => {
33
+ expect(uploadDirsOnContainerDisk(DIRS, 'production', disk({ mounted: ['/app/uploads/public'] }))).toEqual([
34
+ '/app/uploads/private',
35
+ ]);
36
+ });
37
+
38
+ it('never flags in development or test', () => {
39
+ expect(uploadDirsOnContainerDisk(DIRS, 'development', disk())).toEqual([]);
40
+ expect(uploadDirsOnContainerDisk(DIRS, 'test', disk())).toEqual([]);
41
+ });
42
+
43
+ it('never flags outside a container (a plain server disk is persistent)', () => {
44
+ expect(uploadDirsOnContainerDisk(DIRS, 'production', disk({ container: false }))).toEqual([]);
45
+ });
46
+
47
+ it('leaves out a folder it cannot check instead of guessing', () => {
48
+ expect(uploadDirsOnContainerDisk(DIRS, 'production', disk({ broken: ['/app/uploads/public'] }))).toEqual([
49
+ '/app/uploads/private',
50
+ ]);
51
+ });
52
+ });
@@ -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,51 +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
- // Generate public URL
130
154
  const url = `/uploads/users/${userId}/avatar/${filename}`;
131
155
 
132
156
  logger.info({
@@ -176,10 +200,13 @@ class FileStorageService {
176
200
  }
177
201
 
178
202
  /**
179
- * Deletes all media for a user (entire user directory)
203
+ * Deletes all media for a user: the public directory (avatars) AND the
204
+ * private directory (owner-only files).
180
205
  *
181
- * Used by the cleanup job when permanently purging deleted accounts.
182
- * No-op if the user directory doesn't exist.
206
+ * Used by the cleanup job when permanently purging deleted accounts, which
207
+ * promises that nothing of the user remains. It used to delete only the
208
+ * public tier, so private files outlived the account.
209
+ * No-op for a directory that doesn't exist.
183
210
  *
184
211
  * @param userId - User's unique ID
185
212
  *
@@ -190,15 +217,12 @@ class FileStorageService {
190
217
  */
191
218
  async deleteUserMedia(userId: string): Promise<void> {
192
219
  try {
193
- const userDir = this.getUserDir(userId);
194
-
195
- const exists = await this.directoryExists(userDir);
196
- if (!exists) {
197
- return;
220
+ 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
+ }
198
224
  }
199
225
 
200
- await fs.rm(userDir, { recursive: true, force: true });
201
-
202
226
  logger.info({ msg: 'User media deleted successfully', userId });
203
227
  } catch (error) {
204
228
  logger.error({ err: error, msg: 'Failed to delete user media', userId });
@@ -207,25 +231,21 @@ class FileStorageService {
207
231
  }
208
232
 
209
233
  /**
210
- * Gets the full file system path for an avatar
211
- *
212
- * @param userId - User's unique ID
213
- * @param filename - Avatar filename
214
- * @returns Absolute file path
215
- */
216
- getAvatarPath(userId: string, filename: string): string {
217
- return path.join(this.getUserAvatarDir(userId), filename);
218
- }
219
-
220
- /**
221
- * Gets the public URL 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 Public URL 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
- getAvatarUrl(userId: string, filename: string): string {
228
- 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
+ }
229
249
  }
230
250
 
231
251
  /**
@@ -310,21 +330,6 @@ class FileStorageService {
310
330
  return path.join(this.getUserPrivateDir(userId), safeName);
311
331
  }
312
332
 
313
- /**
314
- * Checks if a file exists
315
- *
316
- * @param filePath - Full file path
317
- * @returns True if file exists
318
- */
319
- async fileExists(filePath: string): Promise<boolean> {
320
- try {
321
- await fs.access(filePath);
322
- return true;
323
- } catch {
324
- return false;
325
- }
326
- }
327
-
328
333
  /**
329
334
  * Ensures a directory exists, creates it if not
330
335
  *
@@ -380,6 +385,22 @@ class FileStorageService {
380
385
  throw new InternalError('Failed to initialize file storage', 'STORAGE_INIT_FAILED');
381
386
  }
382
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
+ }
383
404
  }
384
405
 
385
406
  // Export singleton instance