create-tigra 3.3.0 → 4.0.1

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 (207) hide show
  1. package/CHANGELOG.md +151 -0
  2. package/README.md +264 -56
  3. package/bin/create-tigra.js +497 -472
  4. package/lib/patchers/email-verification.patcher.js +72 -10
  5. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  6. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  7. package/modules/email-verification/server/verification.controller.ts +3 -1
  8. package/modules/email-verification/server/verification.service.ts +44 -13
  9. package/package.json +5 -3
  10. package/template/.github/dependabot.yml +47 -0
  11. package/template/.github/workflows/audit.yml +36 -0
  12. package/template/.github/workflows/ci.yml +79 -0
  13. package/template/AGENTS.md +18 -9
  14. package/template/README.md +79 -0
  15. package/template/client/.dockerignore +1 -0
  16. package/template/client/.env.example.production +13 -2
  17. package/template/client/AGENTS.md +13 -5
  18. package/template/client/Dockerfile +186 -14
  19. package/template/client/README.md +92 -21
  20. package/template/client/next.config.ts +1 -1
  21. package/template/client/package-lock.json +15983 -14181
  22. package/template/client/package.json +56 -48
  23. package/template/client/scripts/check-sharp.mjs +53 -0
  24. package/template/client/scripts/next-dev.cjs +5 -1
  25. package/template/client/src/__tests__/proxy.test.ts +92 -0
  26. package/template/client/src/app/healthz/route.ts +16 -0
  27. package/template/client/src/app/layout.tsx +9 -3
  28. package/template/client/src/app/page.tsx +2 -2
  29. package/template/client/src/app/providers.tsx +23 -4
  30. package/template/client/src/components/layout/Header.tsx +7 -3
  31. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  32. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  33. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  34. package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
  35. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  36. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  37. package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
  38. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  39. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  40. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  41. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  42. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  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 +1 -1
  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 +81 -0
  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/session-marker.ts +24 -0
  59. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  60. package/template/client/src/store/__tests__/store.test.ts +44 -0
  61. package/template/client/src/store/index.ts +26 -8
  62. package/template/client/vitest.config.mts +48 -0
  63. package/template/server/.env.example +280 -270
  64. package/template/server/.env.example.production +283 -242
  65. package/template/server/AGENTS.md +13 -4
  66. package/template/server/Dockerfile +176 -14
  67. package/template/server/README.md +108 -0
  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 +66 -4
  71. package/template/server/docs/rate-limits.md +153 -0
  72. package/template/server/docs/testing.md +81 -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 +0 -3
  79. package/template/server/scripts/check-heic.mjs +40 -0
  80. package/template/server/scripts/check-sharp.mjs +53 -0
  81. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  82. package/template/server/src/app.ts +248 -346
  83. package/template/server/src/config/__tests__/env.test.ts +219 -0
  84. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  85. package/template/server/src/config/env.ts +326 -182
  86. package/template/server/src/config/rate-limit.config.ts +157 -106
  87. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  88. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  89. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  90. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  91. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  92. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  93. package/template/server/src/jobs/index.ts +12 -2
  94. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  95. package/template/server/src/jobs/schedule.ts +50 -0
  96. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  97. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  98. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  99. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  100. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  101. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  102. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  103. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  104. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  105. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  106. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  107. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  108. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  109. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  110. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  111. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  112. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  113. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  114. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  115. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  116. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  117. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  118. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  119. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  120. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  121. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  122. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  123. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  124. package/template/server/src/libs/auth.ts +39 -10
  125. package/template/server/src/libs/client-ip.ts +158 -77
  126. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  127. package/template/server/src/libs/cookies.ts +53 -14
  128. package/template/server/src/libs/email-quota.ts +74 -0
  129. package/template/server/src/libs/email.ts +46 -9
  130. package/template/server/src/libs/error-handler.ts +111 -0
  131. package/template/server/src/libs/health-routes.ts +53 -0
  132. package/template/server/src/libs/http.ts +139 -47
  133. package/template/server/src/libs/ip-address.ts +37 -0
  134. package/template/server/src/libs/ip-block.ts +284 -221
  135. package/template/server/src/libs/logger.ts +41 -12
  136. package/template/server/src/libs/monitoring.ts +127 -41
  137. package/template/server/src/libs/observability/sentry.ts +1 -1
  138. package/template/server/src/libs/origin-check.ts +9 -7
  139. package/template/server/src/libs/prisma.ts +47 -4
  140. package/template/server/src/libs/query-counter.ts +71 -59
  141. package/template/server/src/libs/rate-limiting.ts +110 -0
  142. package/template/server/src/libs/redis-required.ts +28 -0
  143. package/template/server/src/libs/redis.ts +27 -1
  144. package/template/server/src/libs/request-id.ts +18 -0
  145. package/template/server/src/libs/requestLogger.ts +112 -17
  146. package/template/server/src/libs/safe-http.ts +101 -0
  147. package/template/server/src/libs/shutdown.ts +87 -0
  148. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  149. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  150. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  151. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  152. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  153. package/template/server/src/libs/storage/file-validator.ts +48 -46
  154. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  155. package/template/server/src/libs/token-hash.ts +18 -0
  156. package/template/server/src/libs/url-safety.ts +127 -121
  157. package/template/server/src/libs/validation-errors.ts +86 -0
  158. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  159. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  160. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  161. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  162. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  163. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  164. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  165. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  166. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  167. package/template/server/src/modules/admin/admin.service.ts +66 -4
  168. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  170. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  171. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  172. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  173. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  174. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  175. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  176. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  177. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  178. package/template/server/src/modules/auth/auth.service.ts +167 -96
  179. package/template/server/src/modules/auth/session.repo.ts +12 -0
  180. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  181. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  182. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  183. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  184. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  185. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  186. package/template/server/src/modules/users/users.controller.ts +9 -38
  187. package/template/server/src/modules/users/users.repo.ts +23 -7
  188. package/template/server/src/modules/users/users.routes.ts +3 -22
  189. package/template/server/src/modules/users/users.schemas.ts +15 -9
  190. package/template/server/src/modules/users/users.service.ts +105 -93
  191. package/template/server/src/scripts/make-admin.ts +48 -0
  192. package/template/server/src/server.ts +48 -26
  193. package/template/server/src/shared/errors/AppError.ts +27 -1
  194. package/template/server/src/shared/errors/errors.ts +42 -5
  195. package/template/server/src/shared/responses/successResponse.ts +22 -3
  196. package/template/server/src/shared/types/index.ts +7 -0
  197. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  198. package/template/server/src/test/integration-helpers.ts +343 -0
  199. package/template/server/src/test/integration-services.ts +74 -0
  200. package/template/server/src/test/integration.global-setup.ts +144 -0
  201. package/template/server/src/test/integration.setup.ts +35 -158
  202. package/template/server/src/test/setup.ts +3 -10
  203. package/template/server/tsconfig.build.json +1 -1
  204. package/template/server/tsconfig.json +1 -0
  205. package/template/server/vitest.config.ts +17 -4
  206. package/template/server/vitest.integration.config.ts +18 -13
  207. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Health checks. Two audiences:
3
+ * - the public probes (/health, /ready, /live in libs/health-routes.ts) answer
4
+ * only up/down-style status, nothing about the internals;
5
+ * - the full report (performHealthCheck) is served to admins only, at
6
+ * GET /api/v1/admin/health.
7
+ */
8
+ import { readFileSync } from 'node:fs';
9
+ import path from 'node:path';
10
+ import { getHeapStatistics } from 'node:v8';
1
11
  import { prisma } from '@libs/prisma.js';
2
12
  import { getRedis } from '@libs/redis.js';
3
13
  import { env } from '@config/env.js';
@@ -12,7 +22,12 @@ export interface HealthCheckResult {
12
22
  uptime: CheckStatus;
13
23
  };
14
24
  timestamp: string;
25
+ /** When the database and Redis were last actually checked (the answer can be up to 5 s old). */
26
+ checkedAt: string;
27
+ /** package.json "version" of the running build, or 'unknown'. */
15
28
  version: string;
29
+ /** The deployed commit (SOURCE_COMMIT, first 12 characters), or null when not set. */
30
+ commit: string | null;
16
31
  environment: string;
17
32
  }
18
33
 
@@ -38,14 +53,12 @@ async function checkDatabase(): Promise<CheckStatus> {
38
53
  status: responseTime < 100 ? 'up' : 'degraded',
39
54
  message: responseTime < 100 ? 'Database is healthy' : 'Database responding slowly',
40
55
  responseTime,
41
- details: {
42
- poolMin: env.DATABASE_POOL_MIN,
43
- poolMax: env.DATABASE_POOL_MAX,
44
- },
56
+ // No pool details: the pool is sized by connection_limit inside DATABASE_URL, which
57
+ // no answer may echo, the admin report included.
45
58
  };
46
59
  } catch (error) {
47
60
  const responseTime = Date.now() - start;
48
- logger.error({ error }, 'Database health check failed');
61
+ logger.error({ err: error }, 'Database health check failed');
49
62
  return {
50
63
  status: 'down',
51
64
  message: 'Database connection failed',
@@ -75,7 +88,7 @@ async function checkRedis(): Promise<CheckStatus> {
75
88
  };
76
89
  } catch (error) {
77
90
  const responseTime = Date.now() - start;
78
- logger.warn({ error }, 'Redis health check failed');
91
+ logger.warn({ err: error }, 'Redis health check failed');
79
92
  return {
80
93
  status: 'down',
81
94
  message: 'Redis connection failed (non-fatal)',
@@ -85,31 +98,86 @@ async function checkRedis(): Promise<CheckStatus> {
85
98
  }
86
99
 
87
100
  /**
88
- * Check memory usage
101
+ * How long one database + Redis check answers every probe (/health,
102
+ * /admin/health, /ready). The probes are public and unlimited (MONITORING_PATHS),
103
+ * so without this each request would run a query: a flood of /health calls
104
+ * would become a flood of database work. 5 s is far below any monitor's
105
+ * interval, so an outage still shows within one probe.
89
106
  */
90
- function checkMemory(): CheckStatus {
91
- const used = process.memoryUsage();
92
- const heapUsedMB = Math.round(used.heapUsed / 1024 / 1024);
93
- const heapTotalMB = Math.round(used.heapTotal / 1024 / 1024);
94
- const rssMB = Math.round(used.rss / 1024 / 1024);
95
- const heapUsagePercent = Math.round((used.heapUsed / used.heapTotal) * 100);
96
-
97
- // Warn if heap usage > 80%
98
- const status = heapUsagePercent > 80 ? 'degraded' : 'up';
99
- const message =
100
- status === 'degraded'
101
- ? `High memory usage: ${heapUsagePercent}%`
102
- : `Memory usage normal: ${heapUsagePercent}%`;
107
+ export const DEPENDENCY_CHECK_TTL_MS = 5_000;
108
+
109
+ interface DependencyChecks {
110
+ database: CheckStatus;
111
+ redis: CheckStatus;
112
+ checkedAt: number;
113
+ }
114
+
115
+ let cachedChecks: DependencyChecks | null = null;
116
+ let checksInFlight: Promise<DependencyChecks> | null = null;
117
+
118
+ /**
119
+ * The database and Redis checks, cached for DEPENDENCY_CHECK_TTL_MS and
120
+ * single-flight: callers arriving while a check runs share its promise
121
+ * instead of starting another (a hung database would otherwise collect one
122
+ * pending query per probe). Failures are cached too, so a down database is
123
+ * not retried by every probe. checkDatabase/checkRedis never throw.
124
+ */
125
+ function checkDependencies(): Promise<DependencyChecks> {
126
+ if (cachedChecks && Date.now() - cachedChecks.checkedAt < DEPENDENCY_CHECK_TTL_MS) {
127
+ return Promise.resolve(cachedChecks);
128
+ }
129
+ if (!checksInFlight) {
130
+ checksInFlight = Promise.all([checkDatabase(), checkRedis()])
131
+ .then(([database, redis]) => {
132
+ cachedChecks = { database, redis, checkedAt: Date.now() };
133
+ return cachedChecks;
134
+ })
135
+ .finally(() => {
136
+ checksInFlight = null;
137
+ });
138
+ }
139
+ return checksInFlight;
140
+ }
141
+
142
+ /** Forget the cached checks, so each test starts with a real check. */
143
+ export function resetHealthCacheForTests(): void {
144
+ cachedChecks = null;
145
+ checksInFlight = null;
146
+ }
147
+
148
+ /** Heap use above this share of the heap LIMIT counts as degraded. */
149
+ export const HEAP_DEGRADED_RATIO = 0.85;
150
+
151
+ /**
152
+ * Check memory usage against the heap LIMIT (v8 heap_size_limit), the point
153
+ * where the process would crash with "heap out of memory".
154
+ *
155
+ * Not against heapTotal: V8 grows heapTotal just ahead of use, so
156
+ * heapUsed/heapTotal sits at 70-99% in a perfectly healthy process (a fresh
157
+ * one already reads 72%), and the old rule reported "degraded" constantly.
158
+ * RSS is reported too: it is what the container's memory limit sees.
159
+ */
160
+ export function checkMemory(
161
+ heap: { used_heap_size: number; heap_size_limit: number } = getHeapStatistics(),
162
+ usage: { rss: number; external: number } = process.memoryUsage(),
163
+ ): CheckStatus {
164
+ const mb = (bytes: number): number => Math.round(bytes / 1024 / 1024);
165
+ const ratio = heap.heap_size_limit > 0 ? heap.used_heap_size / heap.heap_size_limit : 0;
166
+ const heapUsagePercent = Math.round(ratio * 100);
167
+ const status = ratio > HEAP_DEGRADED_RATIO ? 'degraded' : 'up';
103
168
 
104
169
  return {
105
170
  status,
106
- message,
171
+ message:
172
+ status === 'degraded'
173
+ ? `High memory usage: ${heapUsagePercent}% of the heap limit`
174
+ : `Memory usage normal: ${heapUsagePercent}% of the heap limit`,
107
175
  details: {
108
- heapUsedMB,
109
- heapTotalMB,
110
- rssMB,
176
+ heapUsedMB: mb(heap.used_heap_size),
177
+ heapLimitMB: mb(heap.heap_size_limit),
111
178
  heapUsagePercent,
112
- external: Math.round(used.external / 1024 / 1024),
179
+ rssMB: mb(usage.rss),
180
+ externalMB: mb(usage.external),
113
181
  },
114
182
  };
115
183
  }
@@ -145,15 +213,35 @@ function checkUptime(): CheckStatus {
145
213
  }
146
214
 
147
215
  /**
148
- * Perform comprehensive health check
216
+ * The "version" from package.json in `dir` (the server folder: npm scripts run
217
+ * there, and the Docker image copies package.json into WORKDIR /app), or
218
+ * 'unknown' when it cannot be read. Read once; it cannot change while running.
219
+ */
220
+ export function readAppVersion(dir: string = process.cwd()): string {
221
+ try {
222
+ const { version } = JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8')) as { version?: unknown };
223
+ return typeof version === 'string' && version.trim() ? version.trim() : 'unknown';
224
+ } catch {
225
+ return 'unknown';
226
+ }
227
+ }
228
+
229
+ /** A commit SHA shortened to 12 characters (enough to be unique), or null when empty. */
230
+ export function shortCommit(raw: string | undefined): string | null {
231
+ const commit = raw?.trim();
232
+ return commit ? commit.slice(0, 12) : null;
233
+ }
234
+
235
+ const APP_VERSION = readAppVersion();
236
+
237
+ /**
238
+ * Full health report (admins only). Database and Redis come from the shared 5 s cache
239
+ * (checkDependencies); memory and uptime are read fresh, they cost nothing.
149
240
  */
150
241
  export async function performHealthCheck(): Promise<HealthCheckResult> {
151
- const [database, redis, memory, uptime] = await Promise.all([
152
- checkDatabase(),
153
- checkRedis(),
154
- checkMemory(),
155
- checkUptime(),
156
- ]);
242
+ const { database, redis, checkedAt } = await checkDependencies();
243
+ const memory = checkMemory();
244
+ const uptime = checkUptime();
157
245
 
158
246
  // Determine overall status
159
247
  let status: 'healthy' | 'degraded' | 'unhealthy';
@@ -181,22 +269,20 @@ export async function performHealthCheck(): Promise<HealthCheckResult> {
181
269
  uptime,
182
270
  },
183
271
  timestamp: new Date().toISOString(),
184
- version: '1.0.0',
272
+ checkedAt: new Date(checkedAt).toISOString(),
273
+ version: APP_VERSION,
274
+ commit: shortCommit(env.SOURCE_COMMIT),
185
275
  environment: env.NODE_ENV,
186
276
  };
187
277
  }
188
278
 
189
279
  /**
190
- * Simple readiness check (for load balancers)
280
+ * Readiness (for load balancers): ready while the database answers, slow or
281
+ * not. Shares the cached check with /health, so it adds no query of its own.
191
282
  */
192
283
  export async function checkReadiness(): Promise<boolean> {
193
- try {
194
- // Only check database - critical dependency
195
- await prisma.$queryRaw`SELECT 1`;
196
- return true;
197
- } catch {
198
- return false;
199
- }
284
+ const { database } = await checkDependencies();
285
+ return database.status !== 'down';
200
286
  }
201
287
 
202
288
  /**
@@ -24,7 +24,7 @@ let initialized = false;
24
24
  * headers whose value is a URL that may carry a token in its query string.
25
25
  * Keep in step with the client scrubber (client/src/lib/observability/sentry-scrub.ts).
26
26
  */
27
- const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key']);
27
+ const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key', 'x-origin-verify']);
28
28
  const URL_HEADERS = new Set(['referer', 'referrer']);
29
29
 
30
30
  /** Drop the query string: reset/verify tokens and other secrets travel there. */
@@ -1,17 +1,19 @@
1
1
  /**
2
2
  * CSRF defense-in-depth — Origin verification for state-changing requests.
3
3
  *
4
- * With cross-origin cookie deployments (sameSite=none), browsers attach auth
5
- * cookies to cross-site requests. CORS only protects *reading* responses — it
6
- * does not stop the side effects of a forged POST/PUT/PATCH/DELETE. This check
7
- * rejects browser-originated state-changing requests whose Origin header is
8
- * neither the API itself (same-origin) nor a configured CORS origin.
4
+ * The auth cookies are SameSite Strict/Lax (src/libs/cookies.ts), so another
5
+ * website's requests do not carry them. This check is the second line: CORS
6
+ * only protects *reading* responses and does not stop the side effects of a
7
+ * forged POST/PUT/PATCH/DELETE, e.g. from a compromised sibling subdomain
8
+ * (same site, so SameSite does not help there). It rejects browser-originated
9
+ * state-changing requests whose Origin header is neither the API itself
10
+ * (same-origin) nor a configured CORS origin.
9
11
  *
10
12
  * Deliberately conservative:
11
13
  * - No Origin header → ALLOWED. Non-browser clients (curl, Postman,
12
14
  * server-to-server) omit it, and they carry no ambient cookies, so they are
13
- * not CSRF vectors. Browsers always send Origin on cross-site state-changing
14
- * requests, which is the only case this defends against.
15
+ * not CSRF vectors. Browsers always send Origin on cross-origin
16
+ * state-changing requests, which is the only case this defends against.
15
17
  * - allowAllOrigins (development CORS) → ALLOWED.
16
18
  */
17
19
  export function isOriginAllowed(
@@ -1,12 +1,13 @@
1
1
  import { PrismaClient } from '@prisma/client';
2
2
  import { logger } from '@libs/logger.js';
3
3
  import { env } from '@config/env.js';
4
+ import { queryCountExtension } from '@libs/query-counter.js';
4
5
 
5
6
  const globalForPrisma = globalThis as unknown as {
6
7
  prisma: PrismaClient | undefined;
7
8
  };
8
9
 
9
- export const prisma =
10
+ const baseClient =
10
11
  globalForPrisma.prisma ??
11
12
  new PrismaClient({
12
13
  // Note: Connection pool size is configured via DATABASE_URL query params
@@ -29,7 +30,7 @@ export const prisma =
29
30
 
30
31
  // Log slow queries in production (queries taking > 2000ms)
31
32
  if (env.NODE_ENV === 'production') {
32
- prisma.$on('query' as never, (e: { duration: number; query: string }) => {
33
+ baseClient.$on('query' as never, (e: { duration: number; query: string }) => {
33
34
  if (e.duration > 2000) {
34
35
  logger.warn(
35
36
  { duration: e.duration, query: e.query },
@@ -41,15 +42,30 @@ if (env.NODE_ENV === 'production') {
41
42
 
42
43
  // Log all queries in development for debugging
43
44
  if (env.NODE_ENV === 'development') {
44
- prisma.$on('query' as never, (e: { duration: number; query: string }) => {
45
+ baseClient.$on('query' as never, (e: { duration: number; query: string }) => {
45
46
  logger.debug({ duration: e.duration, query: e.query }, 'Database query');
46
47
  });
47
48
  }
48
49
 
49
50
  if (env.NODE_ENV !== 'production') {
50
- globalForPrisma.prisma = prisma;
51
+ globalForPrisma.prisma = baseClient;
51
52
  }
52
53
 
54
+ /**
55
+ * The app's database client. Outside production it carries
56
+ * queryCountExtension, which fills the dev/test X-Query-Count header
57
+ * (libs/query-counter.ts); production gets the plain client, untouched.
58
+ *
59
+ * Typed as the plain PrismaClient on purpose: the extension adds no methods,
60
+ * it only observes each operation, so every caller keeps the same types. One
61
+ * difference: an extended client has no `$on`; register event listeners on
62
+ * baseClient, in this file.
63
+ */
64
+ export const prisma: PrismaClient =
65
+ env.NODE_ENV === 'production'
66
+ ? baseClient
67
+ : (baseClient.$extends(queryCountExtension) as unknown as PrismaClient);
68
+
53
69
  /**
54
70
  * Check if a caught error is Prisma's "record not found" error (P2025).
55
71
  * Use in delete/update operations where the record may have already been
@@ -63,6 +79,33 @@ export function isPrismaNotFound(error: unknown): boolean {
63
79
  );
64
80
  }
65
81
 
82
+ /**
83
+ * Check if a caught error is Prisma's "transaction failed due to a write
84
+ * conflict or a deadlock" (P2034): a concurrent transaction touched the same
85
+ * rows. Treat it as "a parallel request got there first" where that is the
86
+ * meaning (e.g. two refreshes rotating the same token).
87
+ */
88
+ export function isPrismaWriteConflict(error: unknown): boolean {
89
+ return (
90
+ error instanceof Error &&
91
+ 'code' in error &&
92
+ (error as { code: string }).code === 'P2034'
93
+ );
94
+ }
95
+
96
+ /**
97
+ * Check if a caught error is Prisma's unique-constraint violation (P2002): a
98
+ * row with the same unique value already exists. Typical cause: two parallel
99
+ * requests that both checked first and then both inserted.
100
+ */
101
+ export function isPrismaUniqueViolation(error: unknown): boolean {
102
+ return (
103
+ error instanceof Error &&
104
+ 'code' in error &&
105
+ (error as { code: string }).code === 'P2002'
106
+ );
107
+ }
108
+
66
109
  export async function testDatabaseConnection(): Promise<boolean> {
67
110
  try {
68
111
  await prisma.$queryRaw`SELECT 1`;
@@ -1,59 +1,71 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- import type { FastifyInstance } from 'fastify';
3
- import { prisma } from './prisma.js';
4
- import { env } from '@config/env.js';
5
-
6
- /**
7
- * Dev-only per-request Prisma query counter → the `X-Query-Count` response header.
8
- *
9
- * Rides the query events prisma.ts already emits (`{ emit: 'event', level: 'query' }`): an
10
- * AsyncLocalStorage store is entered per request, every emitted query increments it, and the
11
- * total ships back as `X-Query-Count`. This lets a black-box perf/load tester (the fleet's
12
- * perf-tester) see N+1 at the source over plain HTTP — no DB access, no profiler needed.
13
- *
14
- * Note on Prisma N+1: the engine's DataLoader auto-batches relation `include`s and same-tick
15
- * calls, so the queries this counts are the ones that actually matter — sequential awaited
16
- * queries in a loop (`for (...) await prisma.x.find()`), the real application-level N+1.
17
- *
18
- * NEVER active in production: no listener, no header, zero overhead — purely a dev aid.
19
- */
20
- interface QueryCountStore {
21
- count: number;
22
- }
23
-
24
- const als = new AsyncLocalStorage<QueryCountStore>();
25
-
26
- let listenerAttached = false;
27
- function attachQueryListener(): void {
28
- if (listenerAttached) return;
29
- listenerAttached = true;
30
- // Queries outside a counted request (startup, jobs) simply find no store and are ignored.
31
- prisma.$on('query' as never, () => {
32
- const store = als.getStore();
33
- if (store) store.count += 1;
34
- });
35
- }
36
-
37
- /**
38
- * Wire the dev-only `X-Query-Count` header onto every route. Call once with the root app
39
- * instance (top-level, so the hooks are global). No-op in production.
40
- */
41
- export function registerQueryCounter(app: FastifyInstance): void {
42
- if (env.NODE_ENV === 'production') return;
43
- attachQueryListener();
44
-
45
- // Wrap the whole request lifecycle in a fresh store via the callback-style hook: passing
46
- // Fastify's `done` continuation into als.run() means every subsequent hook, the handler, and
47
- // the Prisma calls they make run inside this request's store (the @fastify/request-context
48
- // pattern — more robust than enterWith, which can be lost across the hook boundary).
49
- app.addHook('onRequest', (_request, _reply, done) => {
50
- als.run({ count: 0 }, done);
51
- });
52
-
53
- // onSend can still mutate headers (runs before the body is flushed).
54
- app.addHook('onSend', async (_request, reply, payload) => {
55
- const store = als.getStore();
56
- if (store) reply.header('X-Query-Count', String(store.count));
57
- return payload;
58
- });
59
- }
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import type { FastifyInstance } from 'fastify';
3
+ import { Prisma } from '@prisma/client';
4
+ import { env } from '@config/env.js';
5
+
6
+ /**
7
+ * Dev and test only: the number of Prisma operations a request made, in the
8
+ * `X-Query-Count` response header. This lets a black-box perf/load tester (the
9
+ * fleet's perf-tester) see N+1 at the source over plain HTTP — no DB access, no
10
+ * profiler needed.
11
+ *
12
+ * How it counts: an AsyncLocalStorage store is entered per request, and
13
+ * queryCountExtension (applied to the client in prisma.ts) adds one for every
14
+ * Prisma operation that request runs: model calls (findMany, update, ...) and
15
+ * raw queries ($queryRaw, $executeRaw) alike. It counts operations, not SQL
16
+ * statements (an `include` can add a statement inside one operation).
17
+ *
18
+ * Why an extension and not Prisma's `query` log events: the engine emits those
19
+ * outside the request's async context, so the store was never found and the
20
+ * header always said 0. An extension runs in the caller's context.
21
+ *
22
+ * Note on Prisma N+1: the engine's DataLoader auto-batches relation `include`s and same-tick
23
+ * calls, so the operations this counts are the ones that actually matter — sequential awaited
24
+ * queries in a loop (`for (...) await prisma.x.find()`), the real application-level N+1.
25
+ *
26
+ * NEVER active in production: no extension, no store, no header — purely a dev aid.
27
+ */
28
+ interface QueryCountStore {
29
+ count: number;
30
+ }
31
+
32
+ const als = new AsyncLocalStorage<QueryCountStore>();
33
+
34
+ /**
35
+ * Counts each Prisma operation into the current request's store. Operations
36
+ * outside a counted request (startup, jobs, tests without a request) find no
37
+ * store and are not counted. prisma.ts applies it outside production only.
38
+ */
39
+ export const queryCountExtension = Prisma.defineExtension({
40
+ name: 'query-counter',
41
+ query: {
42
+ $allOperations({ args, query }) {
43
+ const store = als.getStore();
44
+ if (store) store.count += 1;
45
+ return query(args);
46
+ },
47
+ },
48
+ });
49
+
50
+ /**
51
+ * Wire the dev-only `X-Query-Count` header onto every route. Call once with the root app
52
+ * instance (top-level, so the hooks are global). No-op in production.
53
+ */
54
+ export function registerQueryCounter(app: FastifyInstance): void {
55
+ if (env.NODE_ENV === 'production') return;
56
+
57
+ // Wrap the whole request lifecycle in a fresh store via the callback-style hook: passing
58
+ // Fastify's `done` continuation into als.run() means every subsequent hook, the handler, and
59
+ // the Prisma calls they make run inside this request's store (the @fastify/request-context
60
+ // pattern — more robust than enterWith, which can be lost across the hook boundary).
61
+ app.addHook('onRequest', (_request, _reply, done) => {
62
+ als.run({ count: 0 }, done);
63
+ });
64
+
65
+ // onSend can still mutate headers (runs before the body is flushed).
66
+ app.addHook('onSend', async (_request, reply, payload) => {
67
+ const store = als.getStore();
68
+ if (store) reply.header('X-Query-Count', String(store.count));
69
+ return payload;
70
+ });
71
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Rate-limit wiring for the app (limits themselves: src/config/rate-limit.config.ts).
3
+ *
4
+ * - registerRateLimiting(): the onRoute hook that gives every route without its own
5
+ * limit DEFAULT_LIMIT (own counter per route), then @fastify/rate-limit keyed on the
6
+ * verified visitor IP. Over-limit requests on non-auth routes earn IP auto-block
7
+ * strikes; every 429 is a TooManyRequestsError carrying retryAfterSeconds.
8
+ * - registerNotFoundHandler(): unknown URLs answer in the error envelope and share one
9
+ * DEFAULT counter per IP (scanners get 429, then strikes).
10
+ *
11
+ * Never limited: MONITORING_PATHS (health probes come from infrastructure IPs), static
12
+ * /uploads/* (one page can load dozens of public files) and CORS preflights.
13
+ * Kept out of app.ts so tests can mount it on a bare Fastify with the in-memory store.
14
+ */
15
+ import rateLimit from '@fastify/rate-limit';
16
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
17
+ import type { Redis } from 'ioredis';
18
+ import { DEFAULT_LIMIT, RATE_LIMIT_ENABLED } from '@config/rate-limit.config.js';
19
+ import { getClientIp } from '@libs/client-ip.js';
20
+ import { isAuthPath } from '@libs/auth-path.js';
21
+ import { recordRateLimitViolation } from '@libs/ip-block.js';
22
+ import { logger } from '@libs/logger.js';
23
+ import { TooManyRequestsError, describeWait } from '@shared/errors/errors.js';
24
+ import { errorResponse } from '@shared/responses/successResponse.js';
25
+
26
+ /**
27
+ * Health endpoints: exempt from IP blocking, rate limiting and request logging. A blocked
28
+ * probe IP would mark a healthy container as dead and restart-loop it. Matched exactly on
29
+ * the path (query string stripped) so crafted URLs cannot widen the exemption. Must match
30
+ * the route registrations in app.ts.
31
+ */
32
+ export const MONITORING_PATHS = new Set(['/api/v1/health', '/api/v1/ready', '/api/v1/live']);
33
+
34
+ /** Public static files (avatars): cheap file reads, never rate limited. */
35
+ export function isUploadsPath(url: string): boolean {
36
+ return url.startsWith('/uploads/');
37
+ }
38
+
39
+ export interface RateLimitingOptions {
40
+ /** Shared counter store; omit for the in-memory store (tests, RATE_LIMIT_ENABLED=false). */
41
+ redis?: Redis;
42
+ }
43
+
44
+ /**
45
+ * Register the default-limit hook and the rate-limit plugin. Must run BEFORE any route is
46
+ * registered: both only see routes added after them.
47
+ */
48
+ export async function registerRateLimiting(app: FastifyInstance, options: RateLimitingOptions = {}): Promise<void> {
49
+ // @fastify/rate-limit only limits routes that carry config.rateLimit (global: false).
50
+ // This hook runs first for each new route and gives every other route DEFAULT_LIMIT
51
+ // with its OWN counter (the plugin's `global` mode would put them all in one shared
52
+ // counter). Health routes opt out with rateLimit: false.
53
+ app.addHook('onRoute', (routeOptions) => {
54
+ if (routeOptions.config?.rateLimit !== undefined) return; // own limit, or explicitly off
55
+ const methods = Array.isArray(routeOptions.method) ? routeOptions.method : [routeOptions.method];
56
+ if (methods.every((method) => method === 'OPTIONS')) return; // CORS preflight: no work done
57
+ if (isUploadsPath(routeOptions.url) || MONITORING_PATHS.has(routeOptions.url)) return;
58
+ routeOptions.config = { ...routeOptions.config, rateLimit: DEFAULT_LIMIT };
59
+ });
60
+
61
+ // Redis down → skipOnError lets requests through: limits are off until it is back
62
+ // (accepted; see docs/rate-limits.md).
63
+ await app.register(rateLimit, {
64
+ global: false,
65
+ max: DEFAULT_LIMIT.max,
66
+ timeWindow: DEFAULT_LIMIT.timeWindow,
67
+ ...(options.redis ? { redis: options.redis, nameSpace: 'rl:' } : {}),
68
+ skipOnError: true,
69
+ // Key on the verified visitor address (one counter per real visitor, and never an
70
+ // address the visitor wrote itself) — see src/libs/client-ip.ts.
71
+ keyGenerator: (request: FastifyRequest) => getClientIp(request),
72
+ onExceeded: (request: FastifyRequest) => {
73
+ // Auth routes keep their own per-route limit + account lockout; don't let a
74
+ // mistyped password arm the IP-wide auto-ban.
75
+ if (isAuthPath(request)) return;
76
+ void recordRateLimitViolation(getClientIp(request));
77
+ },
78
+ // Thrown, so it reaches the app's error handler like any AppError.
79
+ errorResponseBuilder: (_request, context) => {
80
+ const seconds = Math.max(1, Math.ceil(context.ttl / 1000));
81
+ return new TooManyRequestsError(
82
+ `Too many requests. Try again in ${describeWait(seconds)}.`,
83
+ 'RATE_LIMIT_EXCEEDED',
84
+ seconds,
85
+ );
86
+ },
87
+ });
88
+
89
+ if (!RATE_LIMIT_ENABLED) {
90
+ logger.warn('[RATE-LIMIT] Rate limiting is DISABLED (RATE_LIMIT_ENABLED=false)');
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Unknown URLs: 404 in the error envelope, counted under DEFAULT_LIMIT (one shared counter
96
+ * per IP). A missing file under /uploads/ also lands here and stays exempt, like the
97
+ * static files themselves. Call after registerRateLimiting().
98
+ */
99
+ export function registerNotFoundHandler(app: FastifyInstance): void {
100
+ const limiter = app.rateLimit(DEFAULT_LIMIT);
101
+ app.setNotFoundHandler(
102
+ {
103
+ preHandler: async (request: FastifyRequest, reply: FastifyReply) => {
104
+ if (isUploadsPath(request.url)) return;
105
+ await limiter.call(app, request, reply);
106
+ },
107
+ },
108
+ (_request, reply) => reply.status(404).send(errorResponse('NOT_FOUND', 'Route not found')),
109
+ );
110
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Guard for features that cannot work without Redis: password-reset and
3
+ * email-verification tokens live there, so while Redis is down those flows
4
+ * cannot succeed (rate limits, lockout and blocks merely switch off instead).
5
+ *
6
+ * Call it FIRST, before looking anything up, so every caller gets the same
7
+ * clear 503 SERVICE_UNAVAILABLE whatever the address. Failing later (after the
8
+ * account lookup) would answer 500 for real accounts and the generic success for
9
+ * unknown ones, which both looks broken and reveals who has an account.
10
+ *
11
+ * The check reads the client's connection state, no round trip: the client runs
12
+ * with the offline queue off, so "not ready" means every command would fail now.
13
+ */
14
+ import { getRedis } from '@libs/redis.js';
15
+ import { ServiceUnavailableError } from '@shared/errors/errors.js';
16
+
17
+ /** @param feature what the person asked for, e.g. "Password reset" (starts the message). */
18
+ export function assertRedisReady(feature: string): void {
19
+ let ready: boolean;
20
+ try {
21
+ ready = getRedis().status === 'ready';
22
+ } catch {
23
+ ready = false; // the client could not even be created
24
+ }
25
+ if (!ready) {
26
+ throw new ServiceUnavailableError(`${feature} is temporarily unavailable. Please try again in a few minutes.`);
27
+ }
28
+ }