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,335 +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 { getClientIp } from '@libs/client-ip.js';
27
- import { isAuthPath } from '@libs/auth-path.js';
28
- import { isOriginAllowed } from '@libs/origin-check.js';
29
- import { ForbiddenError } from '@shared/errors/errors.js';
30
- import {
31
- serializerCompiler,
32
- validatorCompiler,
33
- type ZodTypeProvider,
34
- } from 'fastify-type-provider-zod';
35
-
36
- // Import types to register Fastify augmentations
37
- import type {} from '@shared/types/index.js';
38
-
39
- export async function buildApp(): Promise<FastifyInstance> {
40
- const app = Fastify({
41
- logger: false,
42
- // Request-id correlation: honour an inbound X-Request-Id (set by a reverse
43
- // proxy / upstream service) so logs and Sentry events share one id across
44
- // hops; otherwise mint a UUID. Works even with logger:false.
45
- genReqId: (req) => (req.headers['x-request-id'] as string | undefined) ?? randomUUID(),
46
- // Trust proxy headers (X-Forwarded-For) for accurate client IP behind Nginx/load balancer
47
- trustProxy: env.NODE_ENV === 'production',
48
- // Graceful shutdown configuration
49
- forceCloseConnections: true, // Force close idle connections on shutdown
50
- // Env-configurable timeouts (defaults: 30s request, 60s connection).
51
- // Long-running routes (LLM calls, exports) may need 180s+ — raise the
52
- // reverse proxy timeout to match. See REQUEST_TIMEOUT_MS in .env.example.
53
- requestTimeout: env.REQUEST_TIMEOUT_MS,
54
- connectionTimeout: env.CONNECTION_TIMEOUT_MS,
55
- keepAliveTimeout: 5000, // 5s keep-alive timeout
56
- // Request body size limits (prevent DoS attacks)
57
- bodyLimit: 1048576, // 1MB default limit (1024 * 1024)
58
- }).withTypeProvider<ZodTypeProvider>();
59
-
60
- // Set Zod validator and serializer
61
- app.setValidatorCompiler(validatorCompiler);
62
- app.setSerializerCompiler(serializerCompiler);
63
-
64
- // --- Plugins ---
65
- // CORS: Allow all origins in development, specific origin(s) in production
66
- const corsOrigin = env.NODE_ENV === 'development'
67
- ? true
68
- : env.CORS_ORIGIN?.includes(',')
69
- ? env.CORS_ORIGIN.split(',').map((o) => o.trim())
70
- : env.CORS_ORIGIN;
71
-
72
- await app.register(cors, {
73
- origin: corsOrigin,
74
- credentials: true,
75
- methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
76
- });
77
-
78
- // Enhanced security headers for production
79
- await app.register(helmet, {
80
- global: true,
81
- crossOriginResourcePolicy: { policy: 'cross-origin' },
82
- });
83
-
84
-
85
- // Rate limiting: Redis-backed when available, in-memory fallback
86
- if (RATE_LIMIT_ENABLED) {
87
- const redisStore = getRateLimitRedisStore();
88
- await app.register(rateLimit, {
89
- global: false,
90
- max: 100,
91
- timeWindow: '1 minute',
92
- redis: redisStore,
93
- nameSpace: 'rl:',
94
- skipOnError: true, // Gracefully degrade if Redis fails mid-request
95
- // Key the limiter on the real client IP (Cloudflare-aware) so users behind
96
- // a shared CF edge IP aren't counted as one — see src/libs/client-ip.ts.
97
- keyGenerator: (request: FastifyRequest) => getClientIp(request),
98
- onExceeded: (request: FastifyRequest) => {
99
- // Auth routes keep their own per-route limit + account lockout; don't let
100
- // a mistyped password arm the IP-wide auto-ban.
101
- if (isAuthPath(request)) return;
102
- recordRateLimitViolation(getClientIp(request));
103
- },
104
- });
105
- } else {
106
- // Register with effectively no limit so per-route configs don't error
107
- await app.register(rateLimit, {
108
- global: false,
109
- max: 1_000_000,
110
- timeWindow: '1 minute',
111
- });
112
- logger.warn('[RATE-LIMIT] Rate limiting is DISABLED (RATE_LIMIT_ENABLED=false)');
113
- }
114
-
115
- await app.register(cookie, {
116
- secret: env.COOKIE_SECRET || env.JWT_SECRET,
117
- });
118
-
119
- await app.register(jwt, {
120
- secret: env.JWT_SECRET,
121
- cookie: {
122
- cookieName: 'access_token',
123
- signed: false,
124
- },
125
- });
126
-
127
- // Initialize auth helpers after JWT plugin is registered
128
- initAuth(app);
129
-
130
- // Dev-only: count Prisma queries per request → X-Query-Count header (N+1 signal for perf-tester).
131
- // No-op in production. Registered early so its onRequest store is entered before any query runs.
132
- registerQueryCounter(app);
133
-
134
- // File upload handling (multipart/form-data)
135
- await app.register(multipart, {
136
- limits: {
137
- fileSize: env.MAX_FILE_SIZE_MB * 1024 * 1024, // ENV-configurable (default 10MB)
138
- files: 1, // Only one file per request
139
- },
140
- });
141
-
142
- // Initialize file storage (create both upload tiers) BEFORE mounting static,
143
- // so the public root exists when @fastify/static checks it.
144
- await fileStorageService.initialize();
145
-
146
- // Static file serving for uploads — PUBLIC tier ONLY.
147
- // SECURITY: the root is scoped to UPLOAD_PUBLIC_DIR (uploads/public), NOT the
148
- // whole uploads/ tree. The PRIVATE tier (uploads/private) lives OUTSIDE this
149
- // root and is unreachable through /uploads/* — it is served only by the
150
- // auth-gated, owner-scoped route GET /api/v1/files/:filename (filesRoutes).
151
- // The public avatar URL shape is unchanged: serving UPLOAD_PUBLIC_DIR at
152
- // prefix '/uploads/' keeps avatars at /uploads/users/{id}/avatar/x.webp.
153
- await app.register(fastifyStatic, {
154
- root: fileStorageService.getPublicDir(),
155
- prefix: '/uploads/',
156
- });
157
-
158
- // --- Sync permanent IP blocks from DB to Redis ---
159
- await syncBlockedIpsToRedis();
160
-
161
- // Monitoring endpoints exempt from IP blocking and request logging.
162
- // Health probes (Coolify/Docker/K8s/load balancers) come from infrastructure
163
- // IPs that must NEVER be blocked — a blocked probe IP would mark a healthy
164
- // container as dead and restart-loop it. Exact match on the path (query
165
- // string stripped) so the exemption cannot be widened by crafted URLs.
166
- // These paths must match the route registrations below.
167
- const monitoringPaths = new Set(['/api/v1/health', '/api/v1/ready', '/api/v1/live']);
168
-
169
- // --- Request-id echo: surface request.id on the response so a client/proxy
170
- // can correlate a failed call with the server log + Sentry event. Runs first
171
- // so the header is present even when a later hook short-circuits (IP block,
172
- // origin check). request.id is the genReqId value (inbound X-Request-Id or UUID).
173
- app.addHook('onRequest', async (request, reply) => {
174
- reply.header('x-request-id', request.id);
175
- });
176
-
177
- // --- IP Block Check (runs before everything else) ---
178
- app.addHook('onRequest', async (request: FastifyRequest) => {
179
- if (monitoringPaths.has(request.url.split('?')[0])) {
180
- return; // never block health probes
181
- }
182
- if (await isIpBlocked(getClientIp(request))) {
183
- throw new ForbiddenError('Access denied', 'IP_BLOCKED');
184
- }
185
- });
186
-
187
- // --- CSRF defense-in-depth: Origin check on state-changing methods ---
188
- // With sameSite=none cookies (cross-origin deployments), the browser attaches
189
- // auth cookies to cross-site requests. If a browser sends an Origin header on
190
- // a state-changing request, it must be same-origin or a configured CORS
191
- // origin. Requests WITHOUT an Origin header (curl, Postman, server-to-server,
192
- // health probes) are allowed — they carry no ambient cookies and are not
193
- // CSRF vectors. See src/libs/origin-check.ts for the full rationale.
194
- const stateChangingMethods = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
195
- const allowAllOrigins = corsOrigin === true;
196
- const allowedOrigins = new Set<string>(
197
- Array.isArray(corsOrigin) ? corsOrigin : typeof corsOrigin === 'string' ? [corsOrigin] : [],
198
- );
199
-
200
- app.addHook('onRequest', async (request: FastifyRequest) => {
201
- if (!stateChangingMethods.has(request.method)) return;
202
- if (isOriginAllowed(request.headers.origin, request.headers.host, allowedOrigins, allowAllOrigins)) return;
203
- throw new ForbiddenError('Origin not allowed', 'ORIGIN_NOT_ALLOWED');
204
- });
205
-
206
- // --- Request/Response Logging ---
207
- app.addHook('preHandler', async (request) => {
208
- const pathname = request.url.split('?')[0];
209
- if (!monitoringPaths.has(pathname)) {
210
- markRequestStart(request);
211
- }
212
- });
213
-
214
- app.addHook('onResponse', async (request, reply) => {
215
- const pathname = request.url.split('?')[0];
216
- if (!monitoringPaths.has(pathname)) {
217
- logRequestLine(request, reply);
218
- }
219
- });
220
-
221
- // --- Global Error Handler (must be set before routes) ---
222
- app.setErrorHandler((error: FastifyError, request, reply) => {
223
- // AppError — our typed errors (use duck-type check to avoid instanceof issues)
224
- if (isAppError(error)) {
225
- return reply.status(error.statusCode).send(errorResponse(error.code, error.message));
226
- }
227
-
228
- // Zod validation error
229
- if (error.name === 'ZodError') {
230
- return reply.status(422).send(errorResponse('VALIDATION_FAILED', 'Validation failed'));
231
- }
232
-
233
- // Fastify validation error
234
- if (error.validation) {
235
- return reply.status(400).send(
236
- errorResponse(
237
- 'BAD_REQUEST',
238
- error.message || 'Invalid request',
239
- ),
240
- );
241
- }
242
-
243
- // Fastify plugin errors (file size, rate limiting, etc.)
244
- // These have statusCode properties but aren't AppError instances
245
- if (error.statusCode && error.statusCode >= 400 && error.statusCode < 500) {
246
- // Map common Fastify error codes to user-friendly messages
247
- const errorCodeMap: Record<number, { code: string; message: string }> = {
248
- 413: { code: 'FILE_TOO_LARGE', message: 'File size exceeds the maximum allowed limit' },
249
- 429: { code: 'RATE_LIMIT_EXCEEDED', message: 'Too many requests. Please try again later' },
250
- };
251
-
252
- const errorInfo = errorCodeMap[error.statusCode] || {
253
- code: 'BAD_REQUEST',
254
- message: error.message || 'Bad request',
255
- };
256
-
257
- return reply.status(error.statusCode).send(errorResponse(errorInfo.code, errorInfo.message));
258
- }
259
-
260
- // Unexpected error — capture in Sentry (safe no-op when SDK uninitialized),
261
- // then log and return a generic 500. reqId ties the event to the log line.
262
- const requestId = request.id || 'unknown';
263
- Sentry.captureException(error, { extra: { reqId: requestId } });
264
- logger.error(
265
- {
266
- err: error,
267
- requestId,
268
- url: request.url,
269
- method: request.method,
270
- stack: error.stack,
271
- },
272
- `Unhandled error [${requestId}]: ${error.message}`,
273
- );
274
-
275
- return reply.status(500).send(errorResponse('INTERNAL_ERROR', 'Internal server error'));
276
- });
277
-
278
- // --- Monitoring & Health Checks ---
279
- const { performHealthCheck, checkReadiness, checkLiveness } = await import('@libs/monitoring.js');
280
-
281
- // Comprehensive health check (DB + Redis + Memory + Uptime)
282
- app.get('/api/v1/health', async (_request, reply) => {
283
- const health = await performHealthCheck();
284
-
285
- const statusCode = health.status === 'healthy' ? 200 : health.status === 'degraded' ? 200 : 503;
286
-
287
- return reply.status(statusCode).send(
288
- successResponse(
289
- health.status === 'healthy'
290
- ? 'All systems operational'
291
- : health.status === 'degraded'
292
- ? 'Some systems degraded'
293
- : 'System unhealthy',
294
- health,
295
- ),
296
- );
297
- });
298
-
299
- // Readiness probe (for load balancers / K8s)
300
- app.get('/api/v1/ready', async (_request, reply) => {
301
- const ready = await checkReadiness();
302
- const statusCode = ready ? 200 : 503;
303
- return reply.status(statusCode).send(
304
- successResponse(ready ? 'Service is ready' : 'Service not ready', {
305
- ready,
306
- timestamp: new Date().toISOString(),
307
- })
308
- );
309
- });
310
-
311
- // Liveness probe (for container orchestration)
312
- app.get('/api/v1/live', (_request, reply) => {
313
- const alive = checkLiveness();
314
- const statusCode = alive ? 200 : 503;
315
- return reply.status(statusCode).send(
316
- successResponse(alive ? 'Service is alive' : 'Service not alive', {
317
- alive,
318
- timestamp: new Date().toISOString(),
319
- })
320
- );
321
- });
322
-
323
- // --- Routes ---
324
- await app.register(authRoutes, { prefix: '/api/v1' });
325
- await app.register(usersRoutes, { prefix: '/api/v1' });
326
- await app.register(adminRoutes, { prefix: '/api/v1' });
327
- await app.register(filesRoutes, { prefix: '/api/v1' });
328
-
329
- // --- Background Jobs ---
330
- registerJobs(app);
331
-
332
- return app;
333
- }
334
-
335
- 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;