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,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';
@@ -161,7 +249,10 @@ export async function performHealthCheck(): Promise<HealthCheckResult> {
161
249
  status = 'unhealthy'; // Critical: DB is required
162
250
  } else if (
163
251
  database.status === 'degraded' ||
164
- redis.status === 'degraded' ||
252
+ // Redis down is non-fatal (the app keeps serving and reconnects on its
253
+ // own), but rate limits, IP blocks and login lockout are off meanwhile, so
254
+ // monitoring must see it instead of a green "healthy".
255
+ redis.status !== 'up' ||
165
256
  memory.status === 'degraded'
166
257
  ) {
167
258
  status = 'degraded';
@@ -178,22 +269,20 @@ export async function performHealthCheck(): Promise<HealthCheckResult> {
178
269
  uptime,
179
270
  },
180
271
  timestamp: new Date().toISOString(),
181
- version: '1.0.0',
272
+ checkedAt: new Date(checkedAt).toISOString(),
273
+ version: APP_VERSION,
274
+ commit: shortCommit(env.SOURCE_COMMIT),
182
275
  environment: env.NODE_ENV,
183
276
  };
184
277
  }
185
278
 
186
279
  /**
187
- * 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.
188
282
  */
189
283
  export async function checkReadiness(): Promise<boolean> {
190
- try {
191
- // Only check database - critical dependency
192
- await prisma.$queryRaw`SELECT 1`;
193
- return true;
194
- } catch {
195
- return false;
196
- }
284
+ const { database } = await checkDependencies();
285
+ return database.status !== 'down';
197
286
  }
198
287
 
199
288
  /**
@@ -8,11 +8,83 @@
8
8
  * Never hardcode a DSN here or anywhere — it comes only from the environment.
9
9
  */
10
10
  import * as Sentry from '@sentry/node';
11
+ import type { Event } from '@sentry/node';
11
12
  import { env } from '@config/env.js';
12
13
  import { logger } from '@libs/logger.js';
13
14
 
14
15
  let initialized = false;
15
16
 
17
+ /**
18
+ * Privacy rule for error tracking: Sentry gets the error, never the secrets
19
+ * around it. Same policy as the log redaction in libs/logger.ts — without it
20
+ * a 500 during login/register/password change would ship the plaintext
21
+ * password, the auth cookies and any token in the URL to a third party.
22
+ *
23
+ * Header names that must never leave the process (compared lowercase), and
24
+ * headers whose value is a URL that may carry a token in its query string.
25
+ * Keep in step with the client scrubber (client/src/lib/observability/sentry-scrub.ts).
26
+ */
27
+ const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key', 'x-origin-verify']);
28
+ const URL_HEADERS = new Set(['referer', 'referrer']);
29
+
30
+ /** Drop the query string: reset/verify tokens and other secrets travel there. */
31
+ function withoutQuery(url: string): string {
32
+ const cut = url.search(/[?#]/);
33
+ return cut === -1 ? url : url.slice(0, cut);
34
+ }
35
+
36
+ /**
37
+ * Clean a free-form attribute bag (breadcrumb data, span data, trace data):
38
+ * strip queries from anything URL-like (url.full, http.target, referer
39
+ * attributes, …) and drop query/cookie/auth attributes entirely.
40
+ */
41
+ function scrubData(data: Record<string, unknown> | undefined): void {
42
+ if (!data) return;
43
+ for (const key of Object.keys(data)) {
44
+ const lower = key.toLowerCase();
45
+ if (lower.includes('query') || lower.includes('cookie') || lower.includes('authorization')) {
46
+ delete data[key];
47
+ continue;
48
+ }
49
+ const value = data[key];
50
+ if (
51
+ typeof value === 'string' &&
52
+ (lower.includes('url') || lower.includes('referer') || lower.includes('target') || lower === 'from' || lower === 'to')
53
+ ) {
54
+ data[key] = withoutQuery(value);
55
+ }
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Remove request bodies, cookies, auth headers and query strings (including
61
+ * inside the Referer header, span/trace attributes and the transaction name)
62
+ * from an event before it is sent. Exported for tests.
63
+ */
64
+ export function scrubSentryEvent<T extends Event>(event: T): T {
65
+ const request = event.request;
66
+ if (request) {
67
+ delete request.data;
68
+ delete request.cookies;
69
+ delete request.query_string;
70
+ if (request.url) request.url = withoutQuery(request.url);
71
+ if (request.headers) {
72
+ for (const name of Object.keys(request.headers)) {
73
+ const lower = name.toLowerCase();
74
+ if (SECRET_HEADERS.has(lower)) delete request.headers[name];
75
+ else if (URL_HEADERS.has(lower)) request.headers[name] = withoutQuery(request.headers[name]);
76
+ }
77
+ }
78
+ }
79
+
80
+ if (event.transaction) event.transaction = withoutQuery(event.transaction);
81
+ for (const crumb of event.breadcrumbs ?? []) scrubData(crumb.data as Record<string, unknown> | undefined);
82
+ for (const span of event.spans ?? []) scrubData(span.data as Record<string, unknown> | undefined);
83
+ scrubData(event.contexts?.trace?.data as Record<string, unknown> | undefined);
84
+
85
+ return event;
86
+ }
87
+
16
88
  /**
17
89
  * Initialize Sentry only when a DSN is configured.
18
90
  *
@@ -33,6 +105,14 @@ export function initSentry(): void {
33
105
  dsn: env.SENTRY_DSN,
34
106
  tracesSampleRate: env.SENTRY_TRACES_SAMPLE_RATE,
35
107
  environment: env.SENTRY_ENVIRONMENT,
108
+ // Never attach IPs/user identity automatically.
109
+ sendDefaultPii: false,
110
+ // Don't even buffer incoming request bodies (default 'medium' = 10 KB,
111
+ // which would include login/register/password-change payloads).
112
+ integrations: [Sentry.httpIntegration({ maxIncomingRequestBodySize: 'none' })],
113
+ // Last line of defence for anything another integration still attaches.
114
+ beforeSend: (event) => scrubSentryEvent(event),
115
+ beforeSendTransaction: (event) => scrubSentryEvent(event),
36
116
  });
37
117
 
38
118
  initialized = true;
@@ -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
+ }