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.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +160 -44
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +81 -21
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +38 -19
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +18 -4
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/features/auth/types/auth.types.ts +3 -0
- package/template/client/src/instrumentation-client.ts +9 -1
- package/template/client/src/instrumentation.ts +6 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +86 -1
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/security.ts +37 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -269
- package/template/server/.env.example.production +283 -236
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +181 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +19 -6
- package/template/server/prisma/seed.ts +13 -5
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -335
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -171
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +81 -65
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +168 -0
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +113 -0
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +59 -0
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -0
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/account-status.ts +52 -0
- package/template/server/src/libs/auth.ts +51 -12
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +91 -24
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -220
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +131 -42
- package/template/server/src/libs/observability/sentry.ts +80 -0
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +108 -18
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +143 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +104 -83
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +56 -13
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +73 -7
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +332 -49
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +60 -42
- package/template/server/src/modules/auth/auth.schemas.ts +5 -2
- package/template/server/src/modules/auth/auth.service.ts +197 -109
- package/template/server/src/modules/auth/session.repo.ts +12 -12
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +25 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +23 -8
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -1,335 +1,248 @@
|
|
|
1
|
-
import Fastify, { type
|
|
2
|
-
import cors from '@fastify/cors';
|
|
3
|
-
import helmet from '@fastify/helmet';
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
//
|
|
52
|
-
//
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
//
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
//
|
|
143
|
-
//
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
//
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
//
|
|
171
|
-
//
|
|
172
|
-
//
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
)
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
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;
|