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,182 +1,326 @@
1
- import { z } from 'zod';
2
- import dotenv from 'dotenv';
3
-
4
- // Suppress dotenv's informational logs
5
- process.env.DOTENV_CONFIG_QUIET = 'true';
6
- dotenv.config();
7
-
8
- /**
9
- * Treat present-but-empty env vars as unset.
10
- *
11
- * The .env ↔ .env.example sync convention produces `VAR=""` placeholders, and
12
- * Zod's `.optional()` rejects a present-but-empty string (e.g. `.url()` or
13
- * `.min(32)` fails on "") — which killed boot in incident aeaaf94a. Mapping
14
- * "" → undefined makes empty placeholders behave like missing vars: optionals
15
- * stay undefined, defaults kick in. Production presence guards (`!env.VAR`)
16
- * keep working since "" parses to undefined.
17
- */
18
- const optionalEnv = <T extends z.ZodTypeAny>(schema: T): z.ZodPreprocess<T> =>
19
- z.preprocess((v) => (v === '' ? undefined : v), schema);
20
-
21
- const envSchema = z.object({
22
- // --- Application ---
23
- // Fail-closed default: an unset NODE_ENV means production. Development mode
24
- // deliberately relaxes CORS, the Origin check and Secure cookies, so a
25
- // deployment that forgets NODE_ENV must not silently land there. Local dev
26
- // gets NODE_ENV=development from the generated .env; tests set 'test'.
27
- NODE_ENV: optionalEnv(z.enum(['development', 'production', 'test']).default('production')),
28
- PORT: optionalEnv(z.coerce.number().int().min(1).max(65535).default(8000)),
29
- HOST: optionalEnv(z.string().default('0.0.0.0')),
30
-
31
- // --- Server timeouts ---
32
- // Fastify request/connection timeouts. Defaults match the previous hardcoded
33
- // values. Long-running routes (LLM calls, large exports) may need 180s+ —
34
- // remember the reverse proxy (Nginx/Coolify) timeout must be raised to match,
35
- // or the proxy will cut the connection before the server does.
36
- REQUEST_TIMEOUT_MS: optionalEnv(z.coerce.number().int().min(1).default(30000)),
37
- CONNECTION_TIMEOUT_MS: optionalEnv(z.coerce.number().int().min(1).default(60000)),
38
-
39
- // --- Database (MySQL 8.0+) ---
40
- DATABASE_URL: z.string().min(1, 'DATABASE_URL is required'),
41
- DATABASE_POOL_MIN: optionalEnv(z.coerce.number().int().min(1).default(2)),
42
- DATABASE_POOL_MAX: optionalEnv(z.coerce.number().int().min(1).max(1000).default(10)),
43
-
44
- // --- Redis ---
45
- REDIS_URL: optionalEnv(z.string().default('redis://localhost:6379')),
46
- // Retries for a single Redis command. The connection itself reconnects
47
- // forever with capped backoff (see src/libs/redis.ts).
48
- REDIS_MAX_RETRIES: optionalEnv(z.coerce.number().int().min(0).default(3)),
49
- REDIS_CONNECT_TIMEOUT: optionalEnv(z.coerce.number().int().min(1000).default(10000)), // ms
50
-
51
- // --- Rate Limiting ---
52
- RATE_LIMIT_ENABLED: optionalEnv(z.string().default('true').transform((val) => val === 'true')),
53
- RATE_LIMIT_MULTIPLIER: optionalEnv(z.coerce.number().min(0.1).max(100).default(1)),
54
-
55
- // When true, derive the client IP for rate-limiting / IP-blocking from the
56
- // Cloudflare `CF-Connecting-IP` header instead of the socket/X-Forwarded-For
57
- // IP (which is a Cloudflare edge IP behind the proxy — see src/libs/client-ip.ts).
58
- // Default false: the header is client-spoofable, so enable this ONLY when the
59
- // origin accepts traffic exclusively via Cloudflare.
60
- TRUST_CLOUDFLARE: optionalEnv(z.string().default('false').transform((val) => val === 'true')),
61
- RATE_LIMIT_AUTH_LOGIN_MAX: optionalEnv(z.coerce.number().int().min(1).optional()),
62
- RATE_LIMIT_AUTH_REGISTER_MAX: optionalEnv(z.coerce.number().int().min(1).optional()),
63
-
64
- // --- IP Auto-Block (see src/libs/ip-block.ts) ---
65
- // An IP that exceeds rate limits IP_AUTO_BLOCK_THRESHOLD times within
66
- // IP_AUTO_BLOCK_WINDOW_SECONDS is blocked for IP_AUTO_BLOCK_DURATION_SECONDS.
67
- // The threshold targets sustained abuse, not a single burst — a retry-looping
68
- // but legitimate client (or a NAT'd office sharing one IP) must not self-ban.
69
- IP_AUTO_BLOCK_THRESHOLD: optionalEnv(z.coerce.number().int().min(1).default(20)),
70
- IP_AUTO_BLOCK_WINDOW_SECONDS: optionalEnv(z.coerce.number().int().min(1).default(300)),
71
- IP_AUTO_BLOCK_DURATION_SECONDS: optionalEnv(z.coerce.number().int().min(1).default(3600)),
72
-
73
- // --- File Upload ---
74
- MAX_FILE_SIZE_MB: optionalEnv(z.coerce.number().min(1).max(100).default(10)),
75
-
76
- // --- Two-tier upload storage (see src/libs/storage/file-storage.service.ts) ---
77
- // PUBLIC tier: served as static files at /uploads/ — viewable by ANYONE,
78
- // including unauthenticated users (e.g. social-style avatars). @fastify/static
79
- // is scoped to ONLY this directory so it can never serve a private file.
80
- // PRIVATE tier: lives OUTSIDE the static root and is served ONLY through the
81
- // auth-gated streaming route GET /api/v1/files/:filename (owner-scoped).
82
- // Both optional with sensible <cwd>/uploads/{public,private} defaults so a
83
- // clean env still boots; the storage service resolves the defaults at runtime.
84
- UPLOAD_PUBLIC_DIR: optionalEnv(z.string().optional()),
85
- UPLOAD_PRIVATE_DIR: optionalEnv(z.string().optional()),
86
-
87
- // --- JWT Authentication ---
88
- JWT_SECRET: z
89
- .string()
90
- .min(32, 'JWT_SECRET must be at least 32 characters')
91
- // Every secret committed in the template's .env.example files is example
92
- // text starting with CHANGE_ME (43 chars, so it would pass min(32)). This
93
- // guard is what stops an app from booting with that publicly-known signing
94
- // key. Keep any new example secret on the CHANGE_ME prefix; CI asserts it.
95
- .refine(
96
- (s) => !s.startsWith('CHANGE_ME'),
97
- 'JWT_SECRET is still the placeholder — generate one: openssl rand -hex 48',
98
- ),
99
- JWT_ACCESS_EXPIRY: optionalEnv(z.string().default('15m')),
100
- JWT_REFRESH_EXPIRY: optionalEnv(z.string().default('7d')),
101
-
102
- // --- Cookie ---
103
- // Separate secret for cookie signing (defaults to JWT_SECRET if not set)
104
- COOKIE_SECRET: optionalEnv(
105
- z
106
- .string()
107
- .min(32, 'COOKIE_SECRET must be at least 32 characters')
108
- .refine(
109
- (s) => !s.startsWith('CHANGE_ME'),
110
- 'COOKIE_SECRET is still the placeholder — generate one: openssl rand -hex 48',
111
- )
112
- .optional(),
113
- ),
114
-
115
- // Cookie domain for cross-origin deployments (client ≠ server hostname)
116
- // Required when client and API are on different subdomains (e.g., app.example.com + api.example.com)
117
- // Set to the shared parent domain with a leading dot: ".example.com"
118
- // Leave empty for same-origin deployments or local development.
119
- // Applies only to the non-secret auth_session cookie; the token cookies are
120
- // always host-only on the API (see src/libs/cookies.ts).
121
- COOKIE_DOMAIN: optionalEnv(z.string().optional()),
122
-
123
- // --- Account Activation ---
124
- // When true (default), new users start with emailVerifiedAt = null and cannot
125
- // sign in until they verify their email. When false, they count as verified
126
- // immediately. This never touches isActive, which is only the admin ban switch.
127
- REQUIRE_USER_VERIFICATION: optionalEnv(z.string().default('true').transform((val) => val === 'true')),
128
-
129
- // --- CORS ---
130
- // In development: CORS_ORIGIN is optional (allows all origins)
131
- // In production: REQUIRED for security
132
- // Supports comma-separated multiple origins: "https://a.com,https://b.com"
133
- CORS_ORIGIN: optionalEnv(z.string().optional()),
134
-
135
- // --- Logging ---
136
- LOG_LEVEL: optionalEnv(z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace']).default('info')),
137
-
138
- // --- Email (Resend) ---
139
- RESEND_API_KEY: optionalEnv(z.string().min(1).optional()),
140
- RESEND_FROM_EMAIL: optionalEnv(z.string().email().default('onboarding@resend.dev')),
141
- CLIENT_URL: optionalEnv(z.string().url().default('http://localhost:3000')),
142
-
143
- // --- Error Tracking (Optional, Sentry) ---
144
- // All inert without SENTRY_DSN — Sentry init becomes a no-op (see
145
- // src/libs/observability/sentry.ts). Never hardcode a DSN.
146
- SENTRY_DSN: optionalEnv(z.string().url().optional()),
147
- // Fraction of transactions sampled for performance tracing (0..1).
148
- SENTRY_TRACES_SAMPLE_RATE: optionalEnv(z.coerce.number().min(0).max(1).default(0.1)),
149
- // Environment tag attached to Sentry events; defaults to NODE_ENV when unset.
150
- SENTRY_ENVIRONMENT: optionalEnv(z.string().optional()),
151
- });
152
-
153
- const parsed = envSchema.safeParse(process.env);
154
-
155
- if (!parsed.success) {
156
- const formatted = parsed.error.issues
157
- .map((issue) => ` - ${issue.path.join('.')}: ${issue.message}`)
158
- .join('\n');
159
-
160
- console.error(`\nEnvironment validation failed:\n${formatted}\n`);
161
- process.exit(1);
162
- }
163
-
164
- // Validate CORS_ORIGIN in production
165
- if (parsed.data.NODE_ENV === 'production' && !parsed.data.CORS_ORIGIN) {
166
- console.error('\nCORS_ORIGIN is required in production for security\n');
167
- process.exit(1);
168
- }
169
-
170
- // Validate RESEND_API_KEY when email verification is enabled
171
- if (parsed.data.REQUIRE_USER_VERIFICATION && !parsed.data.RESEND_API_KEY) {
172
- console.error('\nRESEND_API_KEY is required when REQUIRE_USER_VERIFICATION is enabled.\nGet your API key from: https://resend.com/api-keys\n');
173
- process.exit(1);
174
- }
175
-
176
- export const env = {
177
- ...parsed.data,
178
- // Default the Sentry environment tag to NODE_ENV when not explicitly set.
179
- SENTRY_ENVIRONMENT: parsed.data.SENTRY_ENVIRONMENT ?? parsed.data.NODE_ENV,
180
- };
181
-
182
- export type Env = z.infer<typeof envSchema>;
1
+ import { z } from 'zod';
2
+ import dotenv from 'dotenv';
3
+
4
+ // Suppress dotenv's informational logs
5
+ process.env.DOTENV_CONFIG_QUIET = 'true';
6
+ dotenv.config();
7
+
8
+ /**
9
+ * Treat present-but-empty env vars as unset.
10
+ *
11
+ * The .env ↔ .env.example sync convention produces `VAR=""` placeholders, and
12
+ * Zod's `.optional()` rejects a present-but-empty string (e.g. `.url()` or
13
+ * `.min(32)` fails on "") — which killed boot in incident aeaaf94a. Mapping
14
+ * "" → undefined makes empty placeholders behave like missing vars: optionals
15
+ * stay undefined, defaults kick in. Production presence guards (`!env.VAR`)
16
+ * keep working since "" parses to undefined.
17
+ */
18
+ const optionalEnv = <T extends z.ZodTypeAny>(schema: T): z.ZodPreprocess<T> =>
19
+ z.preprocess((v) => (v === '' ? undefined : v), schema);
20
+
21
+ /**
22
+ * An on/off switch. Accepts `true` / `false` in any letter case (spaces around
23
+ * ignored) and stops the boot on anything else. A plain `val === 'true'` used
24
+ * to read `True`, `TRUE` or `1` as OFF without a word, which silently switched
25
+ * rate limits or email verification off. Empty or unset means `defaultValue`.
26
+ */
27
+ const envBoolean = (defaultValue: boolean): z.ZodType<boolean> =>
28
+ z
29
+ .preprocess(
30
+ (v) => (typeof v === 'string' && v.trim() !== '' ? v.trim().toLowerCase() : undefined),
31
+ z.enum(['true', 'false'], { message: 'must be true or false' }).default(defaultValue ? 'true' : 'false'),
32
+ )
33
+ .transform((v) => v === 'true');
34
+
35
+ const envSchema = z.object({
36
+ // --- Application ---
37
+ // Fail-closed default: an unset NODE_ENV means production. Development mode
38
+ // deliberately relaxes CORS, the Origin check and Secure cookies, so a
39
+ // deployment that forgets NODE_ENV must not silently land there. Local dev
40
+ // gets NODE_ENV=development from the generated .env; tests set 'test'.
41
+ NODE_ENV: optionalEnv(z.enum(['development', 'production', 'test']).default('production')),
42
+ PORT: optionalEnv(z.coerce.number().int().min(1).max(65535).default(8000)),
43
+ HOST: optionalEnv(z.string().default('0.0.0.0')),
44
+
45
+ // --- Server timeouts ---
46
+ // Fastify request/connection timeouts. Defaults match the previous hardcoded
47
+ // values. Long-running routes (LLM calls, large exports) may need 180s+ —
48
+ // remember the reverse proxy (Nginx/Coolify) timeout must be raised to match,
49
+ // or the proxy will cut the connection before the server does.
50
+ REQUEST_TIMEOUT_MS: optionalEnv(z.coerce.number().int().min(1).default(30000)),
51
+ CONNECTION_TIMEOUT_MS: optionalEnv(z.coerce.number().int().min(1).default(60000)),
52
+
53
+ // --- Database (MySQL 8.4 LTS; 8.0+ works) ---
54
+ // The connection pool is sized INSIDE this URL (`?connection_limit=20&pool_timeout=10`); Prisma
55
+ // reads no separate pool variables. Without connection_limit Prisma uses CPU cores x 2 + 1.
56
+ DATABASE_URL: z.string().min(1, 'DATABASE_URL is required'),
57
+
58
+ // --- Redis ---
59
+ // Required in production (checked below); elsewhere it defaults to the local
60
+ // redis://localhost:6379. See the production check for why.
61
+ REDIS_URL: optionalEnv(z.string().optional()),
62
+ // Retries for a single Redis command. The connection itself reconnects
63
+ // forever with capped backoff (see src/libs/redis.ts).
64
+ REDIS_MAX_RETRIES: optionalEnv(z.coerce.number().int().min(0).default(3)),
65
+ REDIS_CONNECT_TIMEOUT: optionalEnv(z.coerce.number().int().min(1000).default(10000)), // ms
66
+
67
+ // --- Rate Limiting ---
68
+ RATE_LIMIT_ENABLED: envBoolean(true),
69
+ RATE_LIMIT_MULTIPLIER: optionalEnv(z.coerce.number().min(0.1).max(100).default(1)),
70
+ // Per-limit overrides, e.g. "AUTH_LOGIN=100/15m,DEFAULT=300/1m,EMAIL_PER_ADDRESS=3/1h".
71
+ // Parsed and validated (names and format) in src/config/rate-limit.config.ts, which stops
72
+ // the server at boot on a mistake. The multiplier still applies on top of an override.
73
+ RATE_LIMIT_OVERRIDES: optionalEnv(z.string().optional()),
74
+
75
+ // There is no Cloudflare switch: the visitor address is verified per request (Cloudflare is
76
+ // recognised by its published edge ranges), see src/libs/client-ip.ts. A TRUST_CLOUDFLARE
77
+ // value left over on an older deployment is simply ignored (this object is not strict).
78
+ //
79
+ // Optional, recommended behind Cloudflare: a secret that a Cloudflare Transform Rule on YOUR
80
+ // zone adds to every request as the `X-Origin-Verify` header. When set, Cloudflare's visitor
81
+ // header is believed only on requests carrying it, which proves they came through your own
82
+ // zone and not through someone else's Cloudflare Worker. Generate: openssl rand -hex 32
83
+ CLOUDFLARE_ORIGIN_SECRET: optionalEnv(
84
+ z
85
+ .string()
86
+ .min(32, 'CLOUDFLARE_ORIGIN_SECRET must be at least 32 characters')
87
+ .refine((s) => !s.startsWith('CHANGE_ME'), 'CLOUDFLARE_ORIGIN_SECRET is still the placeholder')
88
+ .optional(),
89
+ ),
90
+
91
+ // --- IP Auto-Block (see src/libs/ip-block.ts) ---
92
+ // An IP that exceeds rate limits IP_AUTO_BLOCK_THRESHOLD times within
93
+ // IP_AUTO_BLOCK_WINDOW_SECONDS is blocked for IP_AUTO_BLOCK_DURATION_SECONDS.
94
+ // The threshold targets sustained abuse, not a single burst — a retry-looping
95
+ // but legitimate client (or a NAT'd office sharing one IP) must not self-ban.
96
+ IP_AUTO_BLOCK_THRESHOLD: optionalEnv(z.coerce.number().int().min(1).default(20)),
97
+ IP_AUTO_BLOCK_WINDOW_SECONDS: optionalEnv(z.coerce.number().int().min(1).default(300)),
98
+ IP_AUTO_BLOCK_DURATION_SECONDS: optionalEnv(z.coerce.number().int().min(1).default(3600)),
99
+
100
+ // --- File Upload ---
101
+ MAX_FILE_SIZE_MB: optionalEnv(z.coerce.number().min(1).max(100).default(10)),
102
+
103
+ // --- Two-tier upload storage (see src/libs/storage/file-storage.service.ts) ---
104
+ // PUBLIC tier: served as static files at /uploads/ — viewable by ANYONE,
105
+ // including unauthenticated users (e.g. social-style avatars). @fastify/static
106
+ // is scoped to ONLY this directory so it can never serve a private file.
107
+ // PRIVATE tier: lives OUTSIDE the static root and is served ONLY through the
108
+ // auth-gated streaming route GET /api/v1/files/:filename (owner-scoped).
109
+ // Both optional with sensible <cwd>/uploads/{public,private} defaults so a
110
+ // clean env still boots; the storage service resolves the defaults at runtime.
111
+ UPLOAD_PUBLIC_DIR: optionalEnv(z.string().optional()),
112
+ UPLOAD_PRIVATE_DIR: optionalEnv(z.string().optional()),
113
+
114
+ // --- JWT Authentication ---
115
+ JWT_SECRET: z
116
+ .string()
117
+ .min(32, 'JWT_SECRET must be at least 32 characters')
118
+ // Every secret committed in the template's .env.example files is example
119
+ // text starting with CHANGE_ME (43 chars, so it would pass min(32)). This
120
+ // guard is what stops an app from booting with that publicly-known signing
121
+ // key. Keep any new example secret on the CHANGE_ME prefix; CI asserts it.
122
+ .refine(
123
+ (s) => !s.startsWith('CHANGE_ME'),
124
+ 'JWT_SECRET is still the placeholder — generate one: openssl rand -hex 48',
125
+ ),
126
+ JWT_ACCESS_EXPIRY: optionalEnv(z.string().default('15m')),
127
+ JWT_REFRESH_EXPIRY: optionalEnv(z.string().default('7d')),
128
+
129
+ // --- Cookie ---
130
+ // Separate secret for cookie signing (defaults to JWT_SECRET if not set)
131
+ COOKIE_SECRET: optionalEnv(
132
+ z
133
+ .string()
134
+ .min(32, 'COOKIE_SECRET must be at least 32 characters')
135
+ .refine(
136
+ (s) => !s.startsWith('CHANGE_ME'),
137
+ 'COOKIE_SECRET is still the placeholder — generate one: openssl rand -hex 48',
138
+ )
139
+ .optional(),
140
+ ),
141
+
142
+ // Cookie domain when client and API run on sibling subdomains of one domain
143
+ // (e.g., app.example.com + api.example.com; still the same "site", so the
144
+ // cookies stay SameSite Strict/Lax). Required in that setup.
145
+ // Set to the shared parent domain with a leading dot: ".example.com"
146
+ // Leave empty for same-origin deployments or local development.
147
+ // Applies only to the non-secret auth_session cookie; the token cookies are
148
+ // always host-only on the API (see src/libs/cookies.ts).
149
+ COOKIE_DOMAIN: optionalEnv(z.string().optional()),
150
+
151
+ // --- Account Activation ---
152
+ // When true, new users start with emailVerifiedAt = null and cannot sign in
153
+ // until they verify their email; when false they count as verified at once.
154
+ // The default is false in projects without the email-verification module:
155
+ // only that module provides the verify route, so "on" without it would lock
156
+ // every new user out. Adding the module (at scaffold time or with
157
+ // `create-tigra add email-verification`) switches the default to true.
158
+ // Never touches isActive (the admin ban switch).
159
+ REQUIRE_USER_VERIFICATION: envBoolean(false),
160
+
161
+ // --- CORS ---
162
+ // In development: CORS_ORIGIN is optional (allows all origins)
163
+ // In production: REQUIRED for security
164
+ // Comma-separated bare origins: "https://a.com,https://b.com". Each entry is
165
+ // checked below and exported as env.CORS_ORIGINS.
166
+ CORS_ORIGIN: optionalEnv(z.string().optional()),
167
+
168
+ // --- Logging ---
169
+ LOG_LEVEL: optionalEnv(z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace']).default('info')),
170
+
171
+ // --- Email (Resend) ---
172
+ RESEND_API_KEY: optionalEnv(z.string().min(1).optional()),
173
+ RESEND_FROM_EMAIL: optionalEnv(z.string().email().default('onboarding@resend.dev')),
174
+ // The client's address, used ONLY to build links inside emails (password
175
+ // reset, verification). Required in production when RESEND_API_KEY is set
176
+ // (checked below); otherwise it defaults to http://localhost:3000, so a
177
+ // server-only project without email needs no client address at all.
178
+ CLIENT_URL: optionalEnv(z.string().url().optional()),
179
+
180
+ // --- Error Tracking (Optional, Sentry) ---
181
+ // All inert without SENTRY_DSN — Sentry init becomes a no-op (see
182
+ // src/libs/observability/sentry.ts). Never hardcode a DSN.
183
+ SENTRY_DSN: optionalEnv(z.string().url().optional()),
184
+ // Fraction of transactions sampled for performance tracing (0..1).
185
+ SENTRY_TRACES_SAMPLE_RATE: optionalEnv(z.coerce.number().min(0).max(1).default(0.1)),
186
+ // Environment tag attached to Sentry events; defaults to NODE_ENV when unset.
187
+ SENTRY_ENVIRONMENT: optionalEnv(z.string().optional()),
188
+
189
+ // --- Deployment ---
190
+ // The deployed git commit. Coolify sets it (a predefined variable); you never
191
+ // need to. Shown in GET /api/v1/admin/health; null there when unset.
192
+ SOURCE_COMMIT: optionalEnv(z.string().optional()),
193
+ });
194
+
195
+ const parsed = envSchema.safeParse(process.env);
196
+
197
+ if (!parsed.success) {
198
+ const formatted = parsed.error.issues
199
+ .map((issue) => ` - ${issue.path.join('.')}: ${issue.message}`)
200
+ .join('\n');
201
+
202
+ console.error(`\nEnvironment validation failed:\n${formatted}\n`);
203
+ process.exit(1);
204
+ }
205
+
206
+ // CORS_ORIGIN as a clean list of bare origins ("https://app.example.com").
207
+ // Browsers send Origin as exactly scheme://host[:port], lowercase, and both
208
+ // @fastify/cors and the Origin check compare it exactly. So a trailing slash,
209
+ // a path, "*", an uppercase host or a stray space would silently break every
210
+ // browser request (CORS refuses the answer, the Origin check every write).
211
+ // Refuse those at boot, with the corrected value when one exists. Empty
212
+ // entries (a trailing comma) are ignored.
213
+ const corsOrigins: string[] = [];
214
+ for (const raw of (parsed.data.CORS_ORIGIN ?? '').split(',')) {
215
+ const entry = raw.trim();
216
+ if (!entry) continue;
217
+ let origin: string | null = null;
218
+ try {
219
+ const url = new URL(entry);
220
+ if (url.protocol === 'http:' || url.protocol === 'https:') origin = url.origin;
221
+ } catch {
222
+ // not a URL at all; reported below
223
+ }
224
+ if (origin === null) {
225
+ console.error(
226
+ `\nCORS_ORIGIN entry "${entry}" must be a full origin such as https://app.example.com (no *, path or trailing slash)\n`,
227
+ );
228
+ process.exit(1);
229
+ }
230
+ if (origin !== entry) {
231
+ console.error(`\nCORS_ORIGIN entry "${entry}" is not a bare origin: write it as "${origin}"\n`);
232
+ process.exit(1);
233
+ }
234
+ corsOrigins.push(origin);
235
+ }
236
+
237
+ // Validate CORS_ORIGIN in production
238
+ if (parsed.data.NODE_ENV === 'production' && corsOrigins.length === 0) {
239
+ console.error('\nCORS_ORIGIN is required in production for security\n');
240
+ process.exit(1);
241
+ }
242
+
243
+ // A production client on plain http cannot keep a login: the auth cookies are
244
+ // Secure in production and browsers drop Secure cookies over http (localhost
245
+ // is the exception, so a local production test still works). Coolify's
246
+ // default sslip.io addresses are http, so say it at boot instead of leaving
247
+ // "login works but I stay logged out". A warning, not an exit: some internal
248
+ // setups run on http knowingly. src/libs/cookies.ts warns at runtime too when
249
+ // the API itself is reached over http.
250
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
251
+ const plainHttpOrigins = corsOrigins.filter((o) => o.startsWith('http://') && !LOCAL_HOSTS.has(new URL(o).hostname));
252
+ if (parsed.data.NODE_ENV === 'production' && plainHttpOrigins.length > 0) {
253
+ console.warn(
254
+ `\nWARNING: CORS_ORIGIN uses http:// in production (${plainHttpOrigins.join(', ')}): browsers drop the Secure ` +
255
+ 'login cookies over http, so users cannot stay signed in. Serve the client and API over https.\n',
256
+ );
257
+ }
258
+
259
+ // Require REDIS_URL in production. Redis-backed protections fail OPEN by design
260
+ // (a Redis outage must not take the API down), so a missing URL would not
261
+ // crash anything: inside a container the localhost default reaches nothing,
262
+ // and the app would run with rate limits, login lockout and IP blocks all off
263
+ // while its health check still passes. A missing setting must be loud instead.
264
+ if (parsed.data.NODE_ENV === 'production' && !parsed.data.REDIS_URL) {
265
+ console.error(
266
+ '\nREDIS_URL is required in production: without Redis, rate limits, login lockout and IP blocks are all off\n',
267
+ );
268
+ process.exit(1);
269
+ }
270
+
271
+ // Require CLIENT_URL in production when emails can go out: without it every
272
+ // reset or verification link would point at http://localhost:3000. A
273
+ // production server without a Resend key sends no email, so it needs none.
274
+ if (parsed.data.NODE_ENV === 'production' && parsed.data.RESEND_API_KEY && !parsed.data.CLIENT_URL) {
275
+ console.error(
276
+ '\nCLIENT_URL is required in production when RESEND_API_KEY is set: email links would point to http://localhost:3000\n',
277
+ );
278
+ process.exit(1);
279
+ }
280
+
281
+ // Placeholder email settings in production. Copied as is from
282
+ // .env.example.production, every send fails at Resend and is only logged: with
283
+ // verification on, nobody could finish signing up. Refuse them like the
284
+ // JWT_SECRET placeholder. Resend's test sender only warns (it delivers only to
285
+ // the Resend account owner's own address, but can be a deliberate staging choice).
286
+ if (parsed.data.NODE_ENV === 'production' && parsed.data.RESEND_API_KEY) {
287
+ const key = parsed.data.RESEND_API_KEY;
288
+ const from = parsed.data.RESEND_FROM_EMAIL.toLowerCase();
289
+ if (key.startsWith('CHANGE_ME') || /^re_x+$/i.test(key)) {
290
+ console.error('\nRESEND_API_KEY is still the placeholder: set your Resend API key (https://resend.com/api-keys).\n');
291
+ process.exit(1);
292
+ }
293
+ if (from.endsWith('@yourdomain.com')) {
294
+ console.error(
295
+ '\nRESEND_FROM_EMAIL is still the placeholder (…@yourdomain.com): use an address on a domain verified in Resend.\n',
296
+ );
297
+ process.exit(1);
298
+ }
299
+ if (from === 'onboarding@resend.dev') {
300
+ console.warn(
301
+ "\nWARNING: RESEND_FROM_EMAIL is Resend's test sender (onboarding@resend.dev): it delivers only to your own " +
302
+ "Resend account's address, so users get no email. Use an address on a domain verified in Resend.\n",
303
+ );
304
+ }
305
+ }
306
+
307
+ // Validate RESEND_API_KEY when email verification is enabled
308
+ if (parsed.data.REQUIRE_USER_VERIFICATION && !parsed.data.RESEND_API_KEY) {
309
+ console.error('\nRESEND_API_KEY is required when REQUIRE_USER_VERIFICATION is enabled.\nGet your API key from: https://resend.com/api-keys\n');
310
+ process.exit(1);
311
+ }
312
+
313
+ export const env = {
314
+ ...parsed.data,
315
+ // The checked, trimmed CORS_ORIGIN entries (empty when unset). app.ts uses
316
+ // these for @fastify/cors and the Origin check, never the raw string.
317
+ CORS_ORIGINS: corsOrigins,
318
+ // Outside production a missing REDIS_URL means the local default (checked above).
319
+ REDIS_URL: parsed.data.REDIS_URL ?? 'redis://localhost:6379',
320
+ // A missing CLIENT_URL means the local client (production with email is checked above).
321
+ CLIENT_URL: parsed.data.CLIENT_URL ?? 'http://localhost:3000',
322
+ // Default the Sentry environment tag to NODE_ENV when not explicitly set.
323
+ SENTRY_ENVIRONMENT: parsed.data.SENTRY_ENVIRONMENT ?? parsed.data.NODE_ENV,
324
+ };
325
+
326
+ export type Env = z.infer<typeof envSchema>;