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
@@ -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
  }
@@ -2,6 +2,24 @@
2
2
  * Image Optimization Service
3
3
  *
4
4
  * Handles image processing, optimization, and validation using Sharp.
5
+ *
6
+ * Safety rules for user-uploaded images (avatars are public):
7
+ * - PRIVACY: the output carries NO metadata. sharp strips EXIF/XMP/IPTC by
8
+ * default; never call `.withMetadata()` / `.keepMetadata()` here — it keeps
9
+ * the uploader's GPS location, device and capture time in a public file.
10
+ * Orientation is applied to the pixels first (autoOrient) so photos don't
11
+ * end up sideways once the orientation tag is gone.
12
+ * - MEMORY: a small file can describe a huge picture (a one-colour 16k×16k
13
+ * PNG is ~100 KB but ~1 GB once decoded). The upload size limit only bounds
14
+ * the compressed bytes, so we also cap the decoded pixel count BEFORE
15
+ * decoding, accept only real JPEG/PNG/WebP/HEIF content (judged from the
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.
5
23
  */
6
24
 
7
25
  import sharp from 'sharp';
@@ -9,6 +27,24 @@ import { FILE_UPLOAD_CONSTANTS } from './file-validator.js';
9
27
  import { ValidationError, InternalError } from '@shared/errors/errors.js';
10
28
  import { logger } from '@libs/logger.js';
11
29
 
30
+ /**
31
+ * Largest image we agree to decode: 50 megapixels. Covers 48 MP phone photos
32
+ * (8064×6048); normal photos are 12–24 MP. Bounds decode memory to roughly
33
+ * 200 MB per upload instead of sharp's default ~1 GB (268 MP).
34
+ */
35
+ export const MAX_INPUT_PIXELS = 50_000_000;
36
+
37
+ /** Formats sharp detects from the file's bytes that we accept for avatars ('heif' = HEIC and AVIF). */
38
+ export const ALLOWED_INPUT_FORMATS = ['jpeg', 'png', 'webp', 'heif'] as const;
39
+
40
+ const UNSUPPORTED_FORMAT_MESSAGE = 'Image format is not supported. Use JPEG, PNG, WebP or HEIC.';
41
+
42
+ /** Hard stop for a single image's processing time. */
43
+ const PROCESSING_TIMEOUT_SECONDS = 10;
44
+
45
+ /** sharp options shared by the probe and the pipeline so both enforce the same limit. */
46
+ const INPUT_OPTIONS = { limitInputPixels: MAX_INPUT_PIXELS, autoOrient: true } as const;
47
+
12
48
  /**
13
49
  * Image Optimizer Service
14
50
  *
@@ -19,29 +55,30 @@ class ImageOptimizerService {
19
55
  * Optimizes an image for avatar use
20
56
  *
21
57
  * Process:
22
- * 1. Resize to max 512x512 (preserves aspect ratio)
23
- * 2. Convert to WebP format for best compression
24
- * 3. Compress to ~85% quality
25
- * 4. Strip EXIF metadata for privacy
58
+ * 1. Check the real format and the pixel count before decoding
59
+ * 2. Apply EXIF orientation to the pixels
60
+ * 3. Resize to max 512x512 (preserves aspect ratio)
61
+ * 4. Convert to WebP (~85% quality) with ALL metadata stripped
26
62
  *
27
63
  * @param buffer - Original image buffer
28
64
  * @returns Optimized image buffer in WebP format
29
- * @throws ValidationError if image is invalid
30
- * @throws InternalError if optimization fails
31
- *
32
- * @example
33
- * ```typescript
34
- * const optimized = await imageOptimizerService.optimizeAvatar(imageBuffer);
35
- * ```
65
+ * @throws ValidationError if the image is invalid, too large or an unsupported format
66
+ * @throws InternalError if optimization fails unexpectedly
36
67
  */
37
68
  async optimizeAvatar(buffer: Buffer): Promise<Buffer> {
38
69
  try {
39
- // Validate that buffer contains a valid image
40
- const metadata = await sharp(buffer).metadata();
70
+ // Reads only the header: cheap, and enforces the pixel limit up front.
71
+ const metadata = await sharp(buffer, INPUT_OPTIONS).metadata();
41
72
 
42
73
  if (!metadata.width || !metadata.height) {
43
74
  throw new ValidationError('Unable to read image dimensions', 'INVALID_IMAGE');
44
75
  }
76
+ if (!metadata.format || !(ALLOWED_INPUT_FORMATS as readonly string[]).includes(metadata.format)) {
77
+ throw new ValidationError(UNSUPPORTED_FORMAT_MESSAGE, 'UNSUPPORTED_IMAGE_FORMAT');
78
+ }
79
+ if (metadata.width * metadata.height > MAX_INPUT_PIXELS) {
80
+ throw new ValidationError('Image dimensions are too large', 'IMAGE_TOO_LARGE');
81
+ }
45
82
 
46
83
  logger.info({
47
84
  msg: 'Optimizing avatar image',
@@ -50,23 +87,18 @@ class ImageOptimizerService {
50
87
  originalDimensions: `${metadata.width}x${metadata.height}`,
51
88
  });
52
89
 
53
- // Optimize image
54
- const optimized = await sharp(buffer)
90
+ const optimized = await sharp(buffer, INPUT_OPTIONS)
91
+ .timeout({ seconds: PROCESSING_TIMEOUT_SECONDS })
55
92
  // Resize to max 512x512, preserve aspect ratio
56
93
  .resize(FILE_UPLOAD_CONSTANTS.AVATAR_MAX_DIMENSION, FILE_UPLOAD_CONSTANTS.AVATAR_MAX_DIMENSION, {
57
94
  fit: 'inside', // Preserve aspect ratio, fit within bounds
58
95
  withoutEnlargement: true, // Don't upscale smaller images
59
96
  })
60
- // Convert to WebP with quality optimization
97
+ // Convert to WebP. No withMetadata(): the output keeps no EXIF/GPS/XMP.
61
98
  .webp({
62
99
  quality: 85, // Balance between quality and file size
63
100
  effort: 4, // Compression effort (0-6, higher = better compression but slower)
64
101
  })
65
- // Strip EXIF metadata for privacy
66
- .withMetadata({
67
- exif: {},
68
- icc: undefined,
69
- })
70
102
  .toBuffer();
71
103
 
72
104
  logger.info({
@@ -77,20 +109,34 @@ class ImageOptimizerService {
77
109
 
78
110
  return optimized;
79
111
  } catch (error) {
80
- // Handle Sharp-specific errors
112
+ if (error instanceof ValidationError) {
113
+ throw error;
114
+ }
115
+
116
+ // sharp rejects bad input with plain Errors; map them to client errors.
81
117
  if (error instanceof Error) {
82
- if (error.message.includes('Input buffer contains unsupported image format')) {
83
- throw new ValidationError('Image format is not supported', 'UNSUPPORTED_IMAGE_FORMAT');
118
+ const message = error.message.toLowerCase();
119
+ if (message.includes('pixel limit')) {
120
+ throw new ValidationError('Image dimensions are too large', 'IMAGE_TOO_LARGE');
84
121
  }
85
-
86
- if (error.message.includes('Input file is missing')) {
87
- throw new ValidationError('Invalid image data', 'INVALID_IMAGE');
122
+ if (message.includes('timeout')) {
123
+ throw new ValidationError('Image is too complex to process', 'IMAGE_TOO_COMPLEX');
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
+ }
131
+ if (
132
+ message.includes('unsupported image format') ||
133
+ message.includes('input file is missing') ||
134
+ message.includes('bad seek') ||
135
+ message.includes('corrupt') ||
136
+ message.includes('heif')
137
+ ) {
138
+ throw new ValidationError('Invalid or unsupported image', 'INVALID_IMAGE');
88
139
  }
89
- }
90
-
91
- // Re-throw ValidationError as-is
92
- if (error instanceof ValidationError) {
93
- throw error;
94
140
  }
95
141
 
96
142
  // Wrap unexpected errors
@@ -98,46 +144,6 @@ class ImageOptimizerService {
98
144
  throw new InternalError('Failed to optimize image', 'IMAGE_OPTIMIZATION_FAILED');
99
145
  }
100
146
  }
101
-
102
- /**
103
- * Validates that a buffer contains a valid image
104
- *
105
- * @param buffer - Buffer to validate
106
- * @returns True if buffer is a valid image
107
- * @throws ValidationError if buffer is invalid
108
- *
109
- * @example
110
- * ```typescript
111
- * await imageOptimizerService.validateImageBuffer(buffer);
112
- * ```
113
- */
114
- async validateImageBuffer(buffer: Buffer): Promise<boolean> {
115
- try {
116
- const metadata = await sharp(buffer).metadata();
117
-
118
- if (!metadata.format || !metadata.width || !metadata.height) {
119
- throw new ValidationError('Buffer does not contain a valid image', 'INVALID_IMAGE');
120
- }
121
-
122
- // Check if format is supported
123
- const supportedFormats = ['jpeg', 'png', 'webp', 'gif', 'heif'];
124
- if (!supportedFormats.includes(metadata.format)) {
125
- throw new ValidationError(
126
- `Image format '${metadata.format}' is not supported`,
127
- 'UNSUPPORTED_IMAGE_FORMAT'
128
- );
129
- }
130
-
131
- return true;
132
- } catch (error) {
133
- if (error instanceof ValidationError) {
134
- throw error;
135
- }
136
-
137
- logger.error({ err: error, msg: 'Image validation failed' });
138
- throw new ValidationError('Unable to validate image', 'INVALID_IMAGE');
139
- }
140
- }
141
147
  }
142
148
 
143
149
  // Export singleton instance
@@ -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
+ }
@@ -1,121 +1,127 @@
1
- /**
2
- * URL/IP safety helpers shared across outbound-HTTP code paths.
3
- *
4
- * - `redactUrl` — strips secrets (Telegram bot tokens, query strings)
5
- * from a URL before it reaches any log sink.
6
- * - `isPrivateOrReservedIp`— SSRF building block: returns true for any loopback /
7
- * private / link-local / ULA / reserved address so the
8
- * image-fetch guard can reject internal targets.
9
- *
10
- * Pure, dependency-free, and side-effect-free so they are trivial to unit test.
11
- */
12
-
13
- /**
14
- * Redact a URL so it is safe to log.
15
- *
16
- * Telegram embeds the bot token directly in the request path:
17
- * https://api.telegram.org/bot<TOKEN>/getFile
18
- * https://api.telegram.org/file/bot<TOKEN>/photos/file_1.jpg
19
- * Both forms (`/bot<token>/` and `/file/bot<token>/`) are rewritten to
20
- * `/bot<redacted>/`. Any query string is dropped wholesale (it can also carry
21
- * media tokens / signatures). Non-Telegram URLs pass through unchanged apart
22
- * from query stripping. NEVER throws — an unparseable string is returned with
23
- * just the same path-level redaction applied.
24
- */
25
- export function redactUrl(url: string): string {
26
- if (typeof url !== 'string' || url.length === 0) {
27
- return url;
28
- }
29
-
30
- // Drop the query string (and fragment) — may hold signed tokens.
31
- const noQuery = url.split(/[?#]/, 1)[0];
32
-
33
- // Rewrite Telegram bot-token path segments. The token charset is [A-Za-z0-9_-]
34
- // plus the ':' separating bot-id from secret, e.g. 123456:AAH...
35
- return noQuery.replace(/\/bot[A-Za-z0-9:_-]+/g, '/bot<redacted>');
36
- }
37
-
38
- /**
39
- * True when `addr` is a loopback / private / link-local / ULA / unspecified /
40
- * reserved IP that an SSRF target could use to reach internal infrastructure.
41
- *
42
- * Covers:
43
- * IPv4: 0.0.0.0, 127/8, 10/8, 172.16/12, 192.168/16, 169.254/16, 100.64/10 (CGNAT)
44
- * IPv6: ::, ::1, fc00::/7 (ULA), fe80::/10 (link-local)
45
- * IPv4-mapped IPv6 (::ffff:a.b.c.d) — re-checked against the IPv4 rules.
46
- *
47
- * Unrecognised / unparseable input returns true (fail-closed) — the caller
48
- * uses this purely to BLOCK, so an address it cannot classify is treated as
49
- * unsafe rather than silently allowed.
50
- */
51
- export function isPrivateOrReservedIp(addr: string): boolean {
52
- if (typeof addr !== 'string' || addr.length === 0) {
53
- return true;
54
- }
55
-
56
- const ip = addr.trim().toLowerCase();
57
-
58
- // IPv4-mapped IPv6, e.g. ::ffff:10.0.0.5 or ::ffff:0a00:0005 — extract the v4 tail.
59
- const mapped = ip.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
60
- if (mapped) {
61
- return isPrivateOrReservedIpv4(mapped[1]);
62
- }
63
-
64
- if (ip.includes(':')) {
65
- return isReservedIpv6(ip);
66
- }
67
-
68
- return isPrivateOrReservedIpv4(ip);
69
- }
70
-
71
- function isPrivateOrReservedIpv4(ip: string): boolean {
72
- const parts = ip.split('.');
73
- if (parts.length !== 4) {
74
- return true; // not a clean dotted-quad → block
75
- }
76
-
77
- const octets = parts.map((p) => Number(p));
78
- if (octets.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) {
79
- return true; // malformed → block
80
- }
81
-
82
- const [a, b] = octets;
83
-
84
- if (a === 0) return true; // 0.0.0.0/8 (incl. unspecified)
85
- if (a === 127) return true; // 127.0.0.0/8 loopback
86
- if (a === 10) return true; // 10.0.0.0/8 private
87
- if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12 private
88
- if (a === 192 && b === 168) return true; // 192.168.0.0/16 private
89
- if (a === 169 && b === 254) return true; // 169.254.0.0/16 link-local
90
- if (a === 100 && b >= 64 && b <= 127) return true; // 100.64.0.0/10 CGNAT
91
-
92
- return false;
93
- }
94
-
95
- function isReservedIpv6(ip: string): boolean {
96
- // Normalise: drop zone id (fe80::1%eth0) and any brackets.
97
- const bare = ip.replace(/^\[|\]$/g, '').split('%')[0];
98
-
99
- if (bare === '::' || bare === '::0' || bare === '0:0:0:0:0:0:0:0') return true; // unspecified
100
- if (bare === '::1') return true; // loopback
101
-
102
- // First hextet determines ULA / link-local ranges.
103
- const firstHextet = bare.split(':')[0];
104
- if (firstHextet === '') {
105
- // Address starts with '::' (e.g. '::abcd') — already handled the special
106
- // cases above; remaining such addresses are not in fc00::/7 or fe80::/10.
107
- return false;
108
- }
109
-
110
- const value = parseInt(firstHextet, 16);
111
- if (Number.isNaN(value)) {
112
- return true; // unparseable hextet → block
113
- }
114
-
115
- // fc00::/7 → first 7 bits = 1111110 → first byte 0xfc or 0xfd
116
- if ((value & 0xfe00) === 0xfc00) return true;
117
- // fe80::/10 → first 10 bits = 1111111010 → 0xfe80..0xfebf
118
- if ((value & 0xffc0) === 0xfe80) return true;
119
-
120
- return false;
121
- }
1
+ /**
2
+ * URL/IP safety helpers for outbound HTTP and IP blocking.
3
+ *
4
+ * - `redactUrl` strips secrets (credentials in the URL, query
5
+ * strings, Telegram bot tokens) before a URL reaches
6
+ * any log sink.
7
+ * - `isPrivateOrReservedIp` internal infrastructure: loopback, private,
8
+ * link-local, CGNAT, unique-local, unspecified. Used
9
+ * by IP blocking (never block or auto-block these).
10
+ * - `isForbiddenOutboundIp` everything that is not a public unicast address
11
+ * (the above plus multicast, reserved, documentation,
12
+ * NAT64/6to4 and similar). Used ONLY by the guarded
13
+ * client for user-supplied URLs (libs/safe-http.ts).
14
+ *
15
+ * Two lists on purpose: documentation ranges such as 203.0.113.0/24 and
16
+ * 2001:db8::/32 are not internal (an admin may block them; tests use them as
17
+ * public visitors), yet an outbound request must never go there.
18
+ *
19
+ * Every address is first put into its canonical form (normalizeIp), so a hex
20
+ * IPv4-mapped spelling like ::ffff:7f00:1 is judged as the 127.0.0.1 it is.
21
+ * Pure and side-effect-free, so trivial to unit test.
22
+ */
23
+
24
+ import { BlockList } from 'node:net';
25
+ import { normalizeIp } from '@libs/ip-address.js';
26
+
27
+ /**
28
+ * Redact a URL so it is safe to log.
29
+ *
30
+ * Telegram embeds the bot token directly in the request path:
31
+ * https://api.telegram.org/bot<TOKEN>/getFile
32
+ * https://api.telegram.org/file/bot<TOKEN>/photos/file_1.jpg
33
+ * Both forms (`/bot<token>/` and `/file/bot<token>/`) are rewritten to
34
+ * `/bot<redacted>/`. Any query string is dropped wholesale (it can also carry
35
+ * media tokens / signatures). Non-Telegram URLs pass through unchanged apart
36
+ * from query stripping. NEVER throws — an unparseable string is returned with
37
+ * just the same path-level redaction applied.
38
+ */
39
+ export function redactUrl(url: string): string {
40
+ if (typeof url !== 'string' || url.length === 0) {
41
+ return url;
42
+ }
43
+
44
+ // Drop the query string (and fragment) — may hold API keys or signed tokens —
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');
47
+
48
+ // Rewrite Telegram bot-token path segments. The token charset is [A-Za-z0-9_-]
49
+ // plus the ':' separating bot-id from secret, e.g. 123456:AAH...
50
+ return noQuery.replace(/\/bot[A-Za-z0-9:_-]+/g, '/bot<redacted>');
51
+ }
52
+
53
+ /** Internal infrastructure ranges (isPrivateOrReservedIp). */
54
+ const INTERNAL = new BlockList();
55
+ for (const [net, prefix] of [
56
+ ['0.0.0.0', 8], // "this network", incl. unspecified
57
+ ['10.0.0.0', 8], // private
58
+ ['100.64.0.0', 10], // CGNAT
59
+ ['127.0.0.0', 8], // loopback
60
+ ['169.254.0.0', 16], // link-local (incl. cloud metadata 169.254.169.254)
61
+ ['172.16.0.0', 12], // private
62
+ ['192.168.0.0', 16], // private
63
+ ] as const) INTERNAL.addSubnet(net, prefix, 'ipv4');
64
+ for (const [net, prefix] of [
65
+ ['::', 128], // unspecified
66
+ ['::1', 128], // loopback
67
+ ['fc00::', 7], // unique local
68
+ ['fe80::', 10], // link-local
69
+ ] as const) INTERNAL.addSubnet(net, prefix, 'ipv6');
70
+
71
+ /** Not internal, but never a destination for an outbound request (isForbiddenOutboundIp). */
72
+ const NOT_PUBLIC = new BlockList();
73
+ for (const [net, prefix] of [
74
+ ['192.0.0.0', 24], // IETF protocol assignments
75
+ ['192.0.2.0', 24], // documentation (TEST-NET-1)
76
+ ['192.88.99.0', 24], // 6to4 relay anycast
77
+ ['198.18.0.0', 15], // benchmarking
78
+ ['198.51.100.0', 24], // documentation (TEST-NET-2)
79
+ ['203.0.113.0', 24], // documentation (TEST-NET-3)
80
+ ['224.0.0.0', 4], // multicast
81
+ ['240.0.0.0', 4], // reserved, incl. 255.255.255.255 broadcast
82
+ ] as const) NOT_PUBLIC.addSubnet(net, prefix, 'ipv4');
83
+ for (const [net, prefix] of [
84
+ ['64:ff9b::', 96], // NAT64: would reach any IPv4 address, internal ones too
85
+ ['64:ff9b:1::', 48], // local-use NAT64
86
+ ['100::', 64], // discard
87
+ ['2001::', 23], // IETF protocol assignments (incl. Teredo)
88
+ ['2001:db8::', 32], // documentation
89
+ ['2002::', 16], // 6to4: embeds an IPv4 address
90
+ ['fec0::', 10], // site-local (deprecated)
91
+ ['ff00::', 8], // multicast
92
+ ] as const) NOT_PUBLIC.addSubnet(net, prefix, 'ipv6');
93
+
94
+ /** Canonical address and its family, or undefined for anything that is not an IP literal. */
95
+ function parse(addr: unknown): { ip: string; family: 'ipv4' | 'ipv6' } | undefined {
96
+ if (typeof addr !== 'string') return undefined;
97
+ const ip = normalizeIp(addr.replace(/^\[|\]$/g, ''));
98
+ if (!ip) return undefined;
99
+ const family = ip.includes(':') ? 'ipv6' : 'ipv4';
100
+ // A zone id (fe80::1%eth0) is link-local by definition; BlockList cannot parse it.
101
+ return { ip: family === 'ipv6' ? ip.split('%')[0] : ip, family };
102
+ }
103
+
104
+ /**
105
+ * True when `addr` is internal infrastructure: loopback, private, link-local,
106
+ * CGNAT, unique-local or unspecified (ranges above). IPv4-mapped IPv6, dotted
107
+ * or hex, is judged as its IPv4 address.
108
+ *
109
+ * Unrecognised / unparseable input returns true (fail-closed): callers use this
110
+ * to protect, so an address it cannot classify is treated as internal.
111
+ */
112
+ export function isPrivateOrReservedIp(addr: string): boolean {
113
+ const parsed = parse(addr);
114
+ if (!parsed) return true;
115
+ return INTERNAL.check(parsed.ip, parsed.family);
116
+ }
117
+
118
+ /**
119
+ * True when an outbound request must not go to `addr`: anything internal
120
+ * (isPrivateOrReservedIp) and every other address that is not public unicast.
121
+ * Fail-closed like isPrivateOrReservedIp.
122
+ */
123
+ export function isForbiddenOutboundIp(addr: string): boolean {
124
+ const parsed = parse(addr);
125
+ if (!parsed) return true;
126
+ return INTERNAL.check(parsed.ip, parsed.family) || NOT_PUBLIC.check(parsed.ip, parsed.family);
127
+ }