create-tigra 3.3.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 (203) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +72 -10
  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 +44 -13
  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 +35 -18
  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 +13 -2
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  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/lib/api/__tests__/axios.config.test.ts +183 -0
  41. package/template/client/src/lib/api/api.types.ts +14 -0
  42. package/template/client/src/lib/api/axios.config.ts +101 -15
  43. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  44. package/template/client/src/lib/api/session-events.ts +29 -0
  45. package/template/client/src/lib/constants/routes.ts +12 -0
  46. package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
  47. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  48. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  49. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  50. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  51. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  52. package/template/client/src/lib/utils/error.ts +81 -0
  53. package/template/client/src/lib/utils/form.ts +31 -0
  54. package/template/client/src/lib/utils/paths.ts +18 -0
  55. package/template/client/src/lib/utils/session-marker.ts +24 -0
  56. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  57. package/template/client/src/store/__tests__/store.test.ts +44 -0
  58. package/template/client/src/store/index.ts +26 -8
  59. package/template/client/vitest.config.mts +48 -0
  60. package/template/server/.env.example +280 -270
  61. package/template/server/.env.example.production +283 -242
  62. package/template/server/AGENTS.md +13 -4
  63. package/template/server/Dockerfile +176 -14
  64. package/template/server/docker-compose.yml +4 -2
  65. package/template/server/docs/deployment.md +63 -0
  66. package/template/server/docs/logging.md +52 -4
  67. package/template/server/docs/rate-limits.md +153 -0
  68. package/template/server/docs/testing.md +63 -0
  69. package/template/server/eslint.config.mjs +19 -0
  70. package/template/server/package-lock.json +8784 -8743
  71. package/template/server/package.json +79 -75
  72. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  73. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  74. package/template/server/prisma/schema.prisma +0 -3
  75. package/template/server/scripts/check-heic.mjs +40 -0
  76. package/template/server/scripts/check-sharp.mjs +53 -0
  77. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  78. package/template/server/src/app.ts +248 -346
  79. package/template/server/src/config/__tests__/env.test.ts +219 -0
  80. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  81. package/template/server/src/config/env.ts +326 -182
  82. package/template/server/src/config/rate-limit.config.ts +157 -106
  83. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  84. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  85. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  86. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  87. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  88. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  89. package/template/server/src/jobs/index.ts +12 -2
  90. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  91. package/template/server/src/jobs/schedule.ts +50 -0
  92. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  93. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  94. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  95. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  96. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  97. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  98. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  99. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  100. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  101. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  102. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  103. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  104. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  105. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  106. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  107. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  108. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  109. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  110. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  111. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  112. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  113. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  114. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  115. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  116. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  117. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  118. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  119. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  120. package/template/server/src/libs/auth.ts +39 -10
  121. package/template/server/src/libs/client-ip.ts +158 -77
  122. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  123. package/template/server/src/libs/cookies.ts +53 -14
  124. package/template/server/src/libs/email-quota.ts +74 -0
  125. package/template/server/src/libs/email.ts +46 -9
  126. package/template/server/src/libs/error-handler.ts +111 -0
  127. package/template/server/src/libs/health-routes.ts +53 -0
  128. package/template/server/src/libs/http.ts +139 -47
  129. package/template/server/src/libs/ip-address.ts +37 -0
  130. package/template/server/src/libs/ip-block.ts +284 -221
  131. package/template/server/src/libs/logger.ts +41 -12
  132. package/template/server/src/libs/monitoring.ts +127 -41
  133. package/template/server/src/libs/observability/sentry.ts +1 -1
  134. package/template/server/src/libs/origin-check.ts +9 -7
  135. package/template/server/src/libs/prisma.ts +47 -4
  136. package/template/server/src/libs/query-counter.ts +71 -59
  137. package/template/server/src/libs/rate-limiting.ts +110 -0
  138. package/template/server/src/libs/redis-required.ts +28 -0
  139. package/template/server/src/libs/redis.ts +27 -1
  140. package/template/server/src/libs/request-id.ts +18 -0
  141. package/template/server/src/libs/requestLogger.ts +112 -17
  142. package/template/server/src/libs/safe-http.ts +101 -0
  143. package/template/server/src/libs/shutdown.ts +87 -0
  144. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  145. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  146. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  147. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  148. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  149. package/template/server/src/libs/storage/file-validator.ts +48 -46
  150. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  151. package/template/server/src/libs/token-hash.ts +18 -0
  152. package/template/server/src/libs/url-safety.ts +127 -121
  153. package/template/server/src/libs/validation-errors.ts +86 -0
  154. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  155. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  156. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  157. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  158. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  159. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  160. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  161. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  162. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  163. package/template/server/src/modules/admin/admin.service.ts +66 -4
  164. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  165. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  166. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  167. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  168. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  170. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  171. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  172. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  173. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  174. package/template/server/src/modules/auth/auth.service.ts +167 -96
  175. package/template/server/src/modules/auth/session.repo.ts +12 -0
  176. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  177. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  178. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  179. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  180. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  181. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  182. package/template/server/src/modules/users/users.controller.ts +9 -38
  183. package/template/server/src/modules/users/users.repo.ts +23 -7
  184. package/template/server/src/modules/users/users.routes.ts +3 -22
  185. package/template/server/src/modules/users/users.schemas.ts +15 -9
  186. package/template/server/src/modules/users/users.service.ts +105 -93
  187. package/template/server/src/scripts/make-admin.ts +48 -0
  188. package/template/server/src/server.ts +48 -26
  189. package/template/server/src/shared/errors/AppError.ts +27 -1
  190. package/template/server/src/shared/errors/errors.ts +42 -5
  191. package/template/server/src/shared/responses/successResponse.ts +22 -3
  192. package/template/server/src/shared/types/index.ts +7 -0
  193. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  194. package/template/server/src/test/integration-helpers.ts +343 -0
  195. package/template/server/src/test/integration-services.ts +74 -0
  196. package/template/server/src/test/integration.global-setup.ts +144 -0
  197. package/template/server/src/test/integration.setup.ts +35 -158
  198. package/template/server/src/test/setup.ts +3 -10
  199. package/template/server/tsconfig.build.json +1 -1
  200. package/template/server/tsconfig.json +1 -0
  201. package/template/server/vitest.config.ts +17 -4
  202. package/template/server/vitest.integration.config.ts +18 -13
  203. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -1,346 +1,248 @@
1
- import Fastify, { type FastifyError, type FastifyInstance, type FastifyRequest } from 'fastify';
2
- import cors from '@fastify/cors';
3
- import helmet from '@fastify/helmet';
4
- import rateLimit from '@fastify/rate-limit';
5
- import cookie from '@fastify/cookie';
6
- import jwt from '@fastify/jwt';
7
- import multipart from '@fastify/multipart';
8
- import fastifyStatic from '@fastify/static';
9
- import { randomUUID } from 'node:crypto';
10
- import { env } from '@config/env.js';
11
- import { logger } from '@libs/logger.js';
12
- import { Sentry } from '@libs/observability/sentry.js';
13
- import { markRequestStart, logRequestLine } from '@libs/requestLogger.js';
14
- import { initAuth } from '@libs/auth.js';
15
- import { registerQueryCounter } from '@libs/query-counter.js';
16
- import { isAppError } from '@shared/errors/AppError.js';
17
- import { successResponse, errorResponse } from '@shared/responses/successResponse.js';
18
- import { authRoutes } from '@modules/auth/auth.routes.js';
19
- import { usersRoutes } from '@modules/users/users.routes.js';
20
- import { adminRoutes } from '@modules/admin/admin.routes.js';
21
- import { filesRoutes } from '@modules/files/files.routes.js';
22
- import { fileStorageService } from '@libs/storage/file-storage.service.js';
23
- import { registerJobs } from '@jobs/index.js';
24
- import { RATE_LIMIT_ENABLED, getRateLimitRedisStore } from '@config/rate-limit.config.js';
25
- import { isIpBlocked, recordRateLimitViolation, syncBlockedIpsToRedis } from '@libs/ip-block.js';
26
- import { onRedisReady } from '@libs/redis.js';
27
- import { getClientIp } from '@libs/client-ip.js';
28
- import { isAuthPath } from '@libs/auth-path.js';
29
- import { isOriginAllowed } from '@libs/origin-check.js';
30
- import { ForbiddenError } from '@shared/errors/errors.js';
31
- import {
32
- serializerCompiler,
33
- validatorCompiler,
34
- type ZodTypeProvider,
35
- } from 'fastify-type-provider-zod';
36
-
37
- // Import types to register Fastify augmentations
38
- import type {} from '@shared/types/index.js';
39
-
40
- export async function buildApp(): Promise<FastifyInstance> {
41
- const app = Fastify({
42
- logger: false,
43
- // Request-id correlation: honour an inbound X-Request-Id (set by a reverse
44
- // proxy / upstream service) so logs and Sentry events share one id across
45
- // hops; otherwise mint a UUID. Works even with logger:false.
46
- genReqId: (req) => (req.headers['x-request-id'] as string | undefined) ?? randomUUID(),
47
- // Trust proxy headers (X-Forwarded-For) for accurate client IP behind Nginx/load balancer
48
- trustProxy: env.NODE_ENV === 'production',
49
- // Graceful shutdown configuration
50
- forceCloseConnections: true, // Force close idle connections on shutdown
51
- // Env-configurable timeouts (defaults: 30s request, 60s connection).
52
- // Long-running routes (LLM calls, exports) may need 180s+ — raise the
53
- // reverse proxy timeout to match. See REQUEST_TIMEOUT_MS in .env.example.
54
- requestTimeout: env.REQUEST_TIMEOUT_MS,
55
- connectionTimeout: env.CONNECTION_TIMEOUT_MS,
56
- keepAliveTimeout: 5000, // 5s keep-alive timeout
57
- // Request body size limits (prevent DoS attacks)
58
- bodyLimit: 1048576, // 1MB default limit (1024 * 1024)
59
- }).withTypeProvider<ZodTypeProvider>();
60
-
61
- // Set Zod validator and serializer
62
- app.setValidatorCompiler(validatorCompiler);
63
- app.setSerializerCompiler(serializerCompiler);
64
-
65
- // --- Plugins ---
66
- // CORS: Allow all origins in development, specific origin(s) in production
67
- const corsOrigin = env.NODE_ENV === 'development'
68
- ? true
69
- : env.CORS_ORIGIN?.includes(',')
70
- ? env.CORS_ORIGIN.split(',').map((o) => o.trim())
71
- : env.CORS_ORIGIN;
72
-
73
- await app.register(cors, {
74
- origin: corsOrigin,
75
- credentials: true,
76
- methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
77
- });
78
-
79
- // Enhanced security headers for production
80
- await app.register(helmet, {
81
- global: true,
82
- crossOriginResourcePolicy: { policy: 'cross-origin' },
83
- });
84
-
85
-
86
- // Rate limiting: Redis-backed when available, in-memory fallback
87
- if (RATE_LIMIT_ENABLED) {
88
- const redisStore = getRateLimitRedisStore();
89
- await app.register(rateLimit, {
90
- global: false,
91
- max: 100,
92
- timeWindow: '1 minute',
93
- redis: redisStore,
94
- nameSpace: 'rl:',
95
- skipOnError: true, // Gracefully degrade if Redis fails mid-request
96
- // Key the limiter on the real client IP (Cloudflare-aware) so users behind
97
- // a shared CF edge IP aren't counted as one — see src/libs/client-ip.ts.
98
- keyGenerator: (request: FastifyRequest) => getClientIp(request),
99
- onExceeded: (request: FastifyRequest) => {
100
- // Auth routes keep their own per-route limit + account lockout; don't let
101
- // a mistyped password arm the IP-wide auto-ban.
102
- if (isAuthPath(request)) return;
103
- recordRateLimitViolation(getClientIp(request));
104
- },
105
- });
106
- } else {
107
- // Register with effectively no limit so per-route configs don't error
108
- await app.register(rateLimit, {
109
- global: false,
110
- max: 1_000_000,
111
- timeWindow: '1 minute',
112
- });
113
- logger.warn('[RATE-LIMIT] Rate limiting is DISABLED (RATE_LIMIT_ENABLED=false)');
114
- }
115
-
116
- await app.register(cookie, {
117
- secret: env.COOKIE_SECRET || env.JWT_SECRET,
118
- });
119
-
120
- await app.register(jwt, {
121
- secret: env.JWT_SECRET,
122
- cookie: {
123
- cookieName: 'access_token',
124
- signed: false,
125
- },
126
- });
127
-
128
- // Initialize auth helpers after JWT plugin is registered
129
- initAuth(app);
130
-
131
- // Dev-only: count Prisma queries per request → X-Query-Count header (N+1 signal for perf-tester).
132
- // No-op in production. Registered early so its onRequest store is entered before any query runs.
133
- registerQueryCounter(app);
134
-
135
- // File upload handling (multipart/form-data)
136
- await app.register(multipart, {
137
- limits: {
138
- fileSize: env.MAX_FILE_SIZE_MB * 1024 * 1024, // ENV-configurable (default 10MB)
139
- files: 1, // Only one file per request
140
- },
141
- });
142
-
143
- // Initialize file storage (create both upload tiers) BEFORE mounting static,
144
- // so the public root exists when @fastify/static checks it.
145
- await fileStorageService.initialize();
146
-
147
- // Static file serving for uploads — PUBLIC tier ONLY.
148
- // SECURITY: the root is scoped to UPLOAD_PUBLIC_DIR (uploads/public), NOT the
149
- // whole uploads/ tree. The PRIVATE tier (uploads/private) lives OUTSIDE this
150
- // root and is unreachable through /uploads/* — it is served only by the
151
- // auth-gated, owner-scoped route GET /api/v1/files/:filename (filesRoutes).
152
- // The public avatar URL shape is unchanged: serving UPLOAD_PUBLIC_DIR at
153
- // prefix '/uploads/' keeps avatars at /uploads/users/{id}/avatar/x.webp.
154
- await app.register(fastifyStatic, {
155
- root: fileStorageService.getPublicDir(),
156
- prefix: '/uploads/',
157
- });
158
-
159
- // --- Sync permanent IP blocks from DB to Redis ---
160
- await syncBlockedIpsToRedis();
161
- // Permanent blocks live in MySQL and are only *enforced* through Redis. A
162
- // restarted Redis (or one that was down at boot) comes back without them, so
163
- // re-sync on every reconnect instead of waiting for a server restart.
164
- // syncBlockedIpsToRedis never throws (it logs and returns on failure).
165
- const stopResyncOnReconnect = onRedisReady(() => {
166
- void syncBlockedIpsToRedis();
167
- });
168
- app.addHook('onClose', async () => {
169
- stopResyncOnReconnect();
170
- });
171
-
172
- // Monitoring endpoints exempt from IP blocking and request logging.
173
- // Health probes (Coolify/Docker/K8s/load balancers) come from infrastructure
174
- // IPs that must NEVER be blocked — a blocked probe IP would mark a healthy
175
- // container as dead and restart-loop it. Exact match on the path (query
176
- // string stripped) so the exemption cannot be widened by crafted URLs.
177
- // These paths must match the route registrations below.
178
- const monitoringPaths = new Set(['/api/v1/health', '/api/v1/ready', '/api/v1/live']);
179
-
180
- // --- Request-id echo: surface request.id on the response so a client/proxy
181
- // can correlate a failed call with the server log + Sentry event. Runs first
182
- // so the header is present even when a later hook short-circuits (IP block,
183
- // origin check). request.id is the genReqId value (inbound X-Request-Id or UUID).
184
- app.addHook('onRequest', async (request, reply) => {
185
- reply.header('x-request-id', request.id);
186
- });
187
-
188
- // --- IP Block Check (runs before everything else) ---
189
- app.addHook('onRequest', async (request: FastifyRequest) => {
190
- if (monitoringPaths.has(request.url.split('?')[0])) {
191
- return; // never block health probes
192
- }
193
- if (await isIpBlocked(getClientIp(request))) {
194
- throw new ForbiddenError('Access denied', 'IP_BLOCKED');
195
- }
196
- });
197
-
198
- // --- CSRF defense-in-depth: Origin check on state-changing methods ---
199
- // With sameSite=none cookies (cross-origin deployments), the browser attaches
200
- // auth cookies to cross-site requests. If a browser sends an Origin header on
201
- // a state-changing request, it must be same-origin or a configured CORS
202
- // origin. Requests WITHOUT an Origin header (curl, Postman, server-to-server,
203
- // health probes) are allowed — they carry no ambient cookies and are not
204
- // CSRF vectors. See src/libs/origin-check.ts for the full rationale.
205
- const stateChangingMethods = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
206
- const allowAllOrigins = corsOrigin === true;
207
- const allowedOrigins = new Set<string>(
208
- Array.isArray(corsOrigin) ? corsOrigin : typeof corsOrigin === 'string' ? [corsOrigin] : [],
209
- );
210
-
211
- app.addHook('onRequest', async (request: FastifyRequest) => {
212
- if (!stateChangingMethods.has(request.method)) return;
213
- if (isOriginAllowed(request.headers.origin, request.headers.host, allowedOrigins, allowAllOrigins)) return;
214
- throw new ForbiddenError('Origin not allowed', 'ORIGIN_NOT_ALLOWED');
215
- });
216
-
217
- // --- Request/Response Logging ---
218
- app.addHook('preHandler', async (request) => {
219
- const pathname = request.url.split('?')[0];
220
- if (!monitoringPaths.has(pathname)) {
221
- markRequestStart(request);
222
- }
223
- });
224
-
225
- app.addHook('onResponse', async (request, reply) => {
226
- const pathname = request.url.split('?')[0];
227
- if (!monitoringPaths.has(pathname)) {
228
- logRequestLine(request, reply);
229
- }
230
- });
231
-
232
- // --- Global Error Handler (must be set before routes) ---
233
- app.setErrorHandler((error: FastifyError, request, reply) => {
234
- // AppError — our typed errors (use duck-type check to avoid instanceof issues)
235
- if (isAppError(error)) {
236
- return reply.status(error.statusCode).send(errorResponse(error.code, error.message));
237
- }
238
-
239
- // Zod validation error
240
- if (error.name === 'ZodError') {
241
- return reply.status(422).send(errorResponse('VALIDATION_FAILED', 'Validation failed'));
242
- }
243
-
244
- // Fastify validation error
245
- if (error.validation) {
246
- return reply.status(400).send(
247
- errorResponse(
248
- 'BAD_REQUEST',
249
- error.message || 'Invalid request',
250
- ),
251
- );
252
- }
253
-
254
- // Fastify plugin errors (file size, rate limiting, etc.)
255
- // These have statusCode properties but aren't AppError instances
256
- if (error.statusCode && error.statusCode >= 400 && error.statusCode < 500) {
257
- // Map common Fastify error codes to user-friendly messages
258
- const errorCodeMap: Record<number, { code: string; message: string }> = {
259
- 413: { code: 'FILE_TOO_LARGE', message: 'File size exceeds the maximum allowed limit' },
260
- 429: { code: 'RATE_LIMIT_EXCEEDED', message: 'Too many requests. Please try again later' },
261
- };
262
-
263
- const errorInfo = errorCodeMap[error.statusCode] || {
264
- code: 'BAD_REQUEST',
265
- message: error.message || 'Bad request',
266
- };
267
-
268
- return reply.status(error.statusCode).send(errorResponse(errorInfo.code, errorInfo.message));
269
- }
270
-
271
- // Unexpected error — capture in Sentry (safe no-op when SDK uninitialized),
272
- // then log and return a generic 500. reqId ties the event to the log line.
273
- const requestId = request.id || 'unknown';
274
- Sentry.captureException(error, { extra: { reqId: requestId } });
275
- logger.error(
276
- {
277
- err: error,
278
- requestId,
279
- url: request.url,
280
- method: request.method,
281
- stack: error.stack,
282
- },
283
- `Unhandled error [${requestId}]: ${error.message}`,
284
- );
285
-
286
- return reply.status(500).send(errorResponse('INTERNAL_ERROR', 'Internal server error'));
287
- });
288
-
289
- // --- Monitoring & Health Checks ---
290
- const { performHealthCheck, checkReadiness, checkLiveness } = await import('@libs/monitoring.js');
291
-
292
- // Comprehensive health check (DB + Redis + Memory + Uptime)
293
- app.get('/api/v1/health', async (_request, reply) => {
294
- const health = await performHealthCheck();
295
-
296
- const statusCode = health.status === 'healthy' ? 200 : health.status === 'degraded' ? 200 : 503;
297
-
298
- return reply.status(statusCode).send(
299
- successResponse(
300
- health.status === 'healthy'
301
- ? 'All systems operational'
302
- : health.status === 'degraded'
303
- ? 'Some systems degraded'
304
- : 'System unhealthy',
305
- health,
306
- ),
307
- );
308
- });
309
-
310
- // Readiness probe (for load balancers / K8s)
311
- app.get('/api/v1/ready', async (_request, reply) => {
312
- const ready = await checkReadiness();
313
- const statusCode = ready ? 200 : 503;
314
- return reply.status(statusCode).send(
315
- successResponse(ready ? 'Service is ready' : 'Service not ready', {
316
- ready,
317
- timestamp: new Date().toISOString(),
318
- })
319
- );
320
- });
321
-
322
- // Liveness probe (for container orchestration)
323
- app.get('/api/v1/live', (_request, reply) => {
324
- const alive = checkLiveness();
325
- const statusCode = alive ? 200 : 503;
326
- return reply.status(statusCode).send(
327
- successResponse(alive ? 'Service is alive' : 'Service not alive', {
328
- alive,
329
- timestamp: new Date().toISOString(),
330
- })
331
- );
332
- });
333
-
334
- // --- Routes ---
335
- await app.register(authRoutes, { prefix: '/api/v1' });
336
- await app.register(usersRoutes, { prefix: '/api/v1' });
337
- await app.register(adminRoutes, { prefix: '/api/v1' });
338
- await app.register(filesRoutes, { prefix: '/api/v1' });
339
-
340
- // --- Background Jobs ---
341
- registerJobs(app);
342
-
343
- return app;
344
- }
345
-
346
- export default buildApp;
1
+ import Fastify, { type FastifyInstance, type FastifyRequest, type RouteOptions } from 'fastify';
2
+ import cors from '@fastify/cors';
3
+ import helmet from '@fastify/helmet';
4
+ import cookie from '@fastify/cookie';
5
+ import jwt from '@fastify/jwt';
6
+ import multipart from '@fastify/multipart';
7
+ import fastifyStatic from '@fastify/static';
8
+ import { env } from '@config/env.js';
9
+ import { markRequestStart, logRequestLine } from '@libs/requestLogger.js';
10
+ import { initAuth } from '@libs/auth.js';
11
+ import { registerQueryCounter } from '@libs/query-counter.js';
12
+ import { authRoutes } from '@modules/auth/auth.routes.js';
13
+ import { usersRoutes } from '@modules/users/users.routes.js';
14
+ import { adminRoutes } from '@modules/admin/admin.routes.js';
15
+ import { filesRoutes } from '@modules/files/files.routes.js';
16
+ import { fileStorageService } from '@libs/storage/file-storage.service.js';
17
+ import { MULTIPART_LIMITS } from '@libs/storage/file-validator.js';
18
+ import { registerJobs } from '@jobs/index.js';
19
+ import { RATE_LIMIT_ENABLED } from '@config/rate-limit.config.js';
20
+ import { getIpBlock, syncBlockedIpsToRedis } from '@libs/ip-block.js';
21
+ import { MONITORING_PATHS, registerNotFoundHandler, registerRateLimiting } from '@libs/rate-limiting.js';
22
+ import { getRedis, onRedisReady } from '@libs/redis.js';
23
+ import { getClientIp, TRUSTED_PROXY_RANGES } from '@libs/client-ip.js';
24
+ import { isOriginAllowed } from '@libs/origin-check.js';
25
+ import { registerErrorHandler } from '@libs/error-handler.js';
26
+ import { registerHealthRoutes } from '@libs/health-routes.js';
27
+ import { requestIdFrom } from '@libs/request-id.js';
28
+ import { ForbiddenError, describeWait } from '@shared/errors/errors.js';
29
+ import {
30
+ serializerCompiler,
31
+ validatorCompiler,
32
+ type ZodTypeProvider,
33
+ } from 'fastify-type-provider-zod';
34
+
35
+ // Import types to register Fastify augmentations
36
+ import type {} from '@shared/types/index.js';
37
+
38
+ export interface BuildAppOptions {
39
+ /**
40
+ * Called for every route as it is registered (Fastify's onRoute hook, added
41
+ * before any plugin or route, so it sees all of them). Tests only: the route
42
+ * contract uses it to fail on a route that no test calls
43
+ * (src/test/integration-helpers.ts, routeCoverage). server.ts never sets it.
44
+ */
45
+ onRoute?: (route: RouteOptions) => void;
46
+ }
47
+
48
+ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyInstance> {
49
+ const app = Fastify({
50
+ logger: false,
51
+ // Request-id correlation: honour an inbound X-Request-Id (set by a reverse
52
+ // proxy / upstream service) so logs and Sentry events share one id across
53
+ // hops, but only a short plain one; otherwise mint a UUID. See libs/request-id.ts.
54
+ genReqId: (req) => requestIdFrom(req.headers['x-request-id']),
55
+ // Trust X-Forwarded-* only from our own proxy (loopback / private networks, i.e. Coolify's
56
+ // Traefik), in every environment. request.ip is then the right-most untrusted hop, never an
57
+ // entry the visitor wrote. `true` here would trust every hop, letting any client choose its
58
+ // own rate-limit and block key. Cloudflare is handled in libs/client-ip.ts.
59
+ trustProxy: TRUSTED_PROXY_RANGES,
60
+ // Graceful shutdown configuration
61
+ forceCloseConnections: true, // Force close idle connections on shutdown
62
+ // Env-configurable timeouts (defaults: 30s request, 60s connection).
63
+ // Long-running routes (LLM calls, exports) may need 180s+ — raise the
64
+ // reverse proxy timeout to match. See REQUEST_TIMEOUT_MS in .env.example.
65
+ requestTimeout: env.REQUEST_TIMEOUT_MS,
66
+ connectionTimeout: env.CONNECTION_TIMEOUT_MS,
67
+ keepAliveTimeout: 5000, // 5s keep-alive timeout
68
+ // Request body size limits (prevent DoS attacks)
69
+ bodyLimit: 1048576, // 1MB default limit (1024 * 1024)
70
+ }).withTypeProvider<ZodTypeProvider>();
71
+
72
+ // First, so it runs for every route registered below (plugins included).
73
+ const { onRoute } = options;
74
+ if (onRoute) app.addHook('onRoute', (route) => onRoute(route as RouteOptions));
75
+
76
+ // Set Zod validator and serializer
77
+ app.setValidatorCompiler(validatorCompiler);
78
+ app.setSerializerCompiler(serializerCompiler);
79
+
80
+ // --- Plugins ---
81
+ // CORS: Allow all origins in development, the checked CORS_ORIGIN list
82
+ // otherwise (env.CORS_ORIGINS: bare origins, validated at boot in env.ts).
83
+ const corsOrigin: true | string[] = env.NODE_ENV === 'development' ? true : env.CORS_ORIGINS;
84
+
85
+ await app.register(cors, {
86
+ origin: corsOrigin,
87
+ credentials: true,
88
+ methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
89
+ });
90
+
91
+ // Enhanced security headers for production
92
+ await app.register(helmet, {
93
+ global: true,
94
+ crossOriginResourcePolicy: { policy: 'cross-origin' },
95
+ });
96
+
97
+
98
+ // Rate limiting: the default-limit hook + @fastify/rate-limit, Redis-backed so every
99
+ // server process shares the counters. Before any route. See src/libs/rate-limiting.ts.
100
+ await registerRateLimiting(app, RATE_LIMIT_ENABLED ? { redis: getRedis() } : {});
101
+
102
+ await app.register(cookie, {
103
+ secret: env.COOKIE_SECRET || env.JWT_SECRET,
104
+ });
105
+
106
+ await app.register(jwt, {
107
+ secret: env.JWT_SECRET,
108
+ cookie: {
109
+ cookieName: 'access_token',
110
+ signed: false,
111
+ },
112
+ });
113
+
114
+ // Initialize auth helpers after JWT plugin is registered
115
+ initAuth(app);
116
+
117
+ // Dev-only: count Prisma queries per request → X-Query-Count header (N+1 signal for perf-tester).
118
+ // No-op in production. Registered early so its onRequest store is entered before any query runs.
119
+ registerQueryCounter(app);
120
+
121
+ // File upload handling (multipart/form-data). The field and part caps keep
122
+ // one request from making the server buffer ~1 GB of form fields before the
123
+ // file (see MULTIPART_LIMITS in libs/storage/file-validator.ts).
124
+ await app.register(multipart, {
125
+ limits: {
126
+ fileSize: env.MAX_FILE_SIZE_MB * 1024 * 1024, // ENV-configurable (default 10MB)
127
+ files: 1, // Only one file per request
128
+ ...MULTIPART_LIMITS,
129
+ },
130
+ });
131
+
132
+ // Initialize file storage (create both upload tiers) BEFORE mounting static,
133
+ // so the public root exists when @fastify/static checks it.
134
+ await fileStorageService.initialize();
135
+ // Production container without an uploads volume: say so loudly, every
136
+ // deploy would otherwise delete all avatars without a word.
137
+ fileStorageService.warnIfUploadsNotPersistent();
138
+
139
+ // Static file serving for uploads — PUBLIC tier ONLY.
140
+ // SECURITY: the root is scoped to UPLOAD_PUBLIC_DIR (uploads/public), NOT the
141
+ // whole uploads/ tree. The PRIVATE tier (uploads/private) lives OUTSIDE this
142
+ // root and is unreachable through /uploads/* — it is served only by the
143
+ // auth-gated, owner-scoped route GET /api/v1/files/:filename (filesRoutes).
144
+ // Serving UPLOAD_PUBLIC_DIR at prefix '/uploads/' puts avatars at
145
+ // /uploads/users/{id}/avatar/avatar-<hex>.webp.
146
+ // Cached for a year, immutable: a public file never changes under its name
147
+ // (every new avatar gets a new random name, see file-storage.service.ts), so
148
+ // browsers and CDNs never need to re-check it. Anything else written to the
149
+ // public tier must follow the same rule.
150
+ await app.register(fastifyStatic, {
151
+ root: fileStorageService.getPublicDir(),
152
+ prefix: '/uploads/',
153
+ maxAge: 365 * 24 * 60 * 60 * 1000, // ms
154
+ immutable: true,
155
+ });
156
+
157
+ // --- Sync permanent IP blocks from DB to Redis ---
158
+ await syncBlockedIpsToRedis();
159
+ // Permanent blocks live in MySQL and are only *enforced* through Redis. A
160
+ // restarted Redis (or one that was down at boot) comes back without them, so
161
+ // re-sync on every reconnect instead of waiting for a server restart.
162
+ // syncBlockedIpsToRedis never throws (it logs and returns on failure).
163
+ const stopResyncOnReconnect = onRedisReady(() => {
164
+ void syncBlockedIpsToRedis();
165
+ });
166
+ app.addHook('onClose', async () => {
167
+ stopResyncOnReconnect();
168
+ });
169
+
170
+ // --- Request-id echo: surface request.id on the response so a client/proxy
171
+ // can correlate a failed call with the server log + Sentry event. Runs first
172
+ // so the header is present even when a later hook short-circuits (IP block,
173
+ // origin check). request.id is the genReqId value (inbound X-Request-Id or UUID).
174
+ app.addHook('onRequest', async (request, reply) => {
175
+ reply.header('x-request-id', request.id);
176
+ });
177
+
178
+ // --- IP Block Check (runs before everything else) ---
179
+ app.addHook('onRequest', async (request: FastifyRequest) => {
180
+ if (MONITORING_PATHS.has(request.url.split('?')[0])) {
181
+ return; // never block health probes
182
+ }
183
+ const block = await getIpBlock(getClientIp(request));
184
+ if (!block.blocked) return;
185
+ if (block.permanent) {
186
+ throw new ForbiddenError('Access from your network is blocked.', 'IP_BLOCKED');
187
+ }
188
+ throw new ForbiddenError(
189
+ `Too many requests from your network. Try again in ${describeWait(block.retryAfterSeconds)}.`,
190
+ 'IP_BLOCKED',
191
+ block.retryAfterSeconds,
192
+ );
193
+ });
194
+
195
+ // --- CSRF defense-in-depth: Origin check on state-changing methods ---
196
+ // Second line behind the SameSite cookies (src/libs/cookies.ts): if a browser
197
+ // sends an Origin header on a state-changing request, it must be same-origin
198
+ // or a configured CORS origin (e.g. not a compromised sibling subdomain). Requests WITHOUT an Origin header (curl, Postman, server-to-server,
199
+ // health probes) are allowed — they carry no ambient cookies and are not
200
+ // CSRF vectors. See src/libs/origin-check.ts for the full rationale.
201
+ const stateChangingMethods = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
202
+ const allowAllOrigins = corsOrigin === true;
203
+ const allowedOrigins = new Set<string>(Array.isArray(corsOrigin) ? corsOrigin : []);
204
+
205
+ app.addHook('onRequest', async (request: FastifyRequest) => {
206
+ if (!stateChangingMethods.has(request.method)) return;
207
+ if (isOriginAllowed(request.headers.origin, request.headers.host, allowedOrigins, allowAllOrigins)) return;
208
+ throw new ForbiddenError('Origin not allowed', 'ORIGIN_NOT_ALLOWED');
209
+ });
210
+
211
+ // --- Request/Response Logging ---
212
+ app.addHook('preHandler', async (request) => {
213
+ const pathname = request.url.split('?')[0];
214
+ if (!MONITORING_PATHS.has(pathname)) {
215
+ markRequestStart(request);
216
+ }
217
+ });
218
+
219
+ app.addHook('onResponse', async (request, reply) => {
220
+ const pathname = request.url.split('?')[0];
221
+ if (!MONITORING_PATHS.has(pathname)) {
222
+ logRequestLine(request, reply);
223
+ }
224
+ });
225
+
226
+ // --- Global Error Handler (must be set before routes): see src/libs/error-handler.ts ---
227
+ registerErrorHandler(app);
228
+
229
+ // --- Unknown URLs: error envelope + DEFAULT_LIMIT (see src/libs/rate-limiting.ts) ---
230
+ registerNotFoundHandler(app);
231
+
232
+ // --- Monitoring & Health Checks: public /health, /ready, /live (see src/libs/health-routes.ts) ---
233
+ // The full report is admin-only: GET /api/v1/admin/health (modules/admin).
234
+ registerHealthRoutes(app);
235
+
236
+ // --- Routes ---
237
+ await app.register(authRoutes, { prefix: '/api/v1' });
238
+ await app.register(usersRoutes, { prefix: '/api/v1' });
239
+ await app.register(adminRoutes, { prefix: '/api/v1' });
240
+ await app.register(filesRoutes, { prefix: '/api/v1' });
241
+
242
+ // --- Background Jobs ---
243
+ registerJobs(app);
244
+
245
+ return app;
246
+ }
247
+
248
+ export default buildApp;