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
@@ -6,11 +6,84 @@
6
6
  # BuildKit cache mounts (--mount=type=cache) keep the npm download cache warm
7
7
  # ACROSS builds, so a lockfile-change rebuild re-installs without re-downloading.
8
8
  # Requires the `# syntax` line above; auto-enabled on Docker 23+ / any BuildKit.
9
+ #
10
+ # Every stage uses the same pinned node:24-alpine image (Node 24.22.0,
11
+ # npm 11.19.1, Alpine 3.24). Node 24 is the template's runtime (package.json
12
+ # engines >=24). `npm ci` below fails when package-lock.json was written by an
13
+ # older npm: npm 10 always, and early npm 11 too (11.6.1 leaves out the
14
+ # @emnapi/* entries this npm requires). Write lockfiles with npm 11.19 or newer.
9
15
 
10
16
  # ===================================================================
11
- # Stage 1: Dependencies (cached layer)
17
+ # Stage 1: libvips that runs on any x86-64 CPU
12
18
  # ===================================================================
13
- FROM node:20-alpine@sha256:fb4cd12c85ee03686f6af5362a0b0d56d50c58a04632e6c0fb8363f609372293 AS dependencies
19
+ # Why this stage exists: sharp's prebuilt addon and the libvips it bundles
20
+ # need an x86-64-v2 CPU (SSE4.2/POPCNT). Many VPS hosts present an older
21
+ # virtual CPU (e.g. "QEMU Virtual CPU"), where the prebuilt sharp refuses to
22
+ # load and the server crashes at start. So we compile a pinned libvips release
23
+ # for the generic x86-64 baseline and build sharp's addon against it (stage 2).
24
+ #
25
+ # KEEP THIS STAGE BYTE-IDENTICAL in server/Dockerfile and client/Dockerfile,
26
+ # so one rule set builds both images. Identical text also lets a plain
27
+ # `docker build` host reuse the compiled layer across the two apps. On
28
+ # Coolify (measured): redeploys of the same app on the same server reused it,
29
+ # but the two apps did not share it, and a change to a build-time variable
30
+ # compiled it again (Coolify passes those into the build). An uncached
31
+ # compile takes about 6-7 min on a small shared VPS.
32
+ #
33
+ # Version coupling: every sharp release needs a minimum libvips (the
34
+ # "config.libvips" range in sharp's package.json, e.g. ">=8.18.7" for sharp
35
+ # 0.35.5). When a sharp upgrade needs more than LIBVIPS_VERSION, bump
36
+ # LIBVIPS_VERSION and LIBVIPS_SHA256 (from the libvips release page) in BOTH
37
+ # Dockerfiles. Stage 2 stops the build with a clear message if you forget.
38
+ FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS libvips
39
+
40
+ ARG LIBVIPS_VERSION=8.18.7
41
+ ARG LIBVIPS_SHA256=5baaead3b0bb20ffdb9e9ff09aa9fda08620923df77b63b436654cb5e0b3bf94
42
+
43
+ # Compilers and codec headers. python3 serves node-gyp in the stage that
44
+ # builds FROM this one. Every -dev package here needs its runtime library in
45
+ # the production stage's apk list (keep the two lists in sync).
46
+ RUN apk add --no-cache \
47
+ build-base python3 curl xz meson ninja pkgconf \
48
+ glib-dev expat-dev libjpeg-turbo-dev libpng-dev libwebp-dev \
49
+ tiff-dev lcms2-dev libheif-dev libexif-dev
50
+
51
+ ENV PKG_CONFIG_PATH=/opt/vips/lib/pkgconfig \
52
+ LD_LIBRARY_PATH=/opt/vips/lib
53
+
54
+ # --auto-features=disabled turns every optional dependency off; only the
55
+ # formats we use are enabled: JPEG/PNG/WebP/HEIF/TIFF (plus the built-in GIF
56
+ # loader, which Next's image optimizer accepts), colour profiles, and EXIF
57
+ # (needed to read orientation and strip metadata). The rarely used PPM,
58
+ # Analyze and Radiance loaders are off to shrink the parser attack surface.
59
+ # -march=x86-64 is the baseline every x86-64 CPU supports (other
60
+ # architectures keep the compiler default). -j 2 bounds memory on small
61
+ # build hosts.
62
+ RUN set -eu; \
63
+ if [ "$(uname -m)" = "x86_64" ]; then \
64
+ export CFLAGS="-march=x86-64 -mtune=generic" CXXFLAGS="-march=x86-64 -mtune=generic"; \
65
+ fi; \
66
+ curl -fsSL --retry 3 -o /tmp/vips.tar.xz \
67
+ "https://github.com/libvips/libvips/releases/download/v${LIBVIPS_VERSION}/vips-${LIBVIPS_VERSION}.tar.xz"; \
68
+ echo "${LIBVIPS_SHA256} /tmp/vips.tar.xz" | sha256sum -c -; \
69
+ tar -xJf /tmp/vips.tar.xz -C /tmp; \
70
+ meson setup /tmp/vips-build "/tmp/vips-${LIBVIPS_VERSION}" \
71
+ --prefix=/opt/vips --libdir=lib --buildtype=release --auto-features=disabled \
72
+ -Djpeg=enabled -Dpng=enabled -Dwebp=enabled -Dheif=enabled -Dtiff=enabled \
73
+ -Dlcms=enabled -Dzlib=enabled -Dexif=enabled \
74
+ -Dexamples=false -Dppm=false -Danalyze=false -Dradiance=false; \
75
+ meson compile -C /tmp/vips-build -j 2; \
76
+ meson install -C /tmp/vips-build; \
77
+ test "$(pkg-config --modversion vips-cpp)" = "${LIBVIPS_VERSION}"; \
78
+ rm -rf /tmp/vips-build "/tmp/vips-${LIBVIPS_VERSION}" /tmp/vips.tar.xz
79
+
80
+ # ===================================================================
81
+ # Stage 2: Production dependencies + CPU-safe sharp addon
82
+ # ===================================================================
83
+ # Built FROM the libvips stage because compiling sharp's addon needs the
84
+ # compilers and every codec -dev package that vips-cpp.pc references. Only
85
+ # /app/node_modules leaves this stage.
86
+ FROM libvips AS dependencies
14
87
 
15
88
  # Install production dependencies only
16
89
  WORKDIR /app
@@ -29,7 +102,7 @@ RUN --mount=type=cache,target=/root/.npm \
29
102
  fi
30
103
 
31
104
  # Add the Prisma CLI to the production node_modules so the runtime image can
32
- # run `npx prisma migrate deploy` at container start (see CMD in stage 3).
105
+ # run `npx prisma migrate deploy` at container start (see CMD in stage 4).
33
106
  # `prisma` is a devDependency (correct for local dev), so the prod-only install
34
107
  # above does NOT include it — without this step, npx would try to download the
35
108
  # CLI from the registry on every container boot. Pinned to the exact
@@ -40,10 +113,60 @@ RUN --mount=type=cache,target=/root/.npm \
40
113
  RUN --mount=type=cache,target=/root/.npm npm install --no-save --no-audit --no-fund \
41
114
  "prisma@$(node -p "require('@prisma/client/package.json').version")"
42
115
 
116
+ # Build sharp's native addon against /opt/vips. sharp loads
117
+ # node_modules/sharp/src/build/Release/sharp-<platform>-<version>.node BEFORE
118
+ # its prebuilt addon and without the prebuilt's x86-64-v2 check, so this file
119
+ # is what makes sharp work on older CPUs. Keep this block identical in
120
+ # server/Dockerfile and client/Dockerfile.
121
+ # - It runs after every npm install above, so it targets the sharp version
122
+ # actually installed (read from its package.json, never hard-coded).
123
+ # - SHARP_FORCE_GLOBAL_LIBVIPS makes sharp skip its own libvips version
124
+ # check, so the block checks sharp's "config.libvips" range itself.
125
+ # - node-addon-api and node-gyp are build tools sharp requires but does not
126
+ # install. They go to /tmp/sharp-build (exact pins inside sharp's declared
127
+ # ranges; --ignore-scripts, since neither needs an install script and their
128
+ # unlocked transitive packages must not run code here) and never reach the
129
+ # lockfile or the runtime image.
130
+ # - npm_config_nodedir points node-gyp at this image's own Node headers, so
131
+ # nothing is downloaded and the addon matches the runtime Node exactly.
132
+ # - Intermediate build files are dropped; only the .node file stays, also
133
+ # staged in /opt/sharp-addon for stages that copy it explicitly.
134
+ RUN --mount=type=cache,target=/root/.npm \
135
+ set -eu; \
136
+ npm install --prefix /tmp/sharp-build --no-save --no-audit --no-fund --ignore-scripts \
137
+ node-addon-api@8.9.2 node-gyp@12.4.0; \
138
+ if [ ! -d node_modules/sharp ]; then \
139
+ echo "ERROR: node_modules/sharp is missing. If this app no longer uses sharp, delete this build step and the libvips stage." >&2; \
140
+ exit 1; \
141
+ fi; \
142
+ cd node_modules/sharp; \
143
+ version="$(node -p "require('./package.json').version")"; \
144
+ need="$(node -p "require('./package.json').config.libvips")"; \
145
+ have="$(pkg-config --modversion vips-cpp)"; \
146
+ if ! node -e "process.exit(require('semver').satisfies(process.argv[1], process.argv[2]) ? 0 : 1)" "$have" "$need"; then \
147
+ echo "ERROR: sharp ${version} needs libvips ${need}, but this image builds libvips ${have}. Raise LIBVIPS_VERSION and LIBVIPS_SHA256 in BOTH server/Dockerfile and client/Dockerfile." >&2; \
148
+ exit 1; \
149
+ fi; \
150
+ if [ "$(uname -m)" = "x86_64" ]; then \
151
+ export CFLAGS="-march=x86-64 -mtune=generic" CXXFLAGS="-march=x86-64 -mtune=generic"; \
152
+ fi; \
153
+ SHARP_FORCE_GLOBAL_LIBVIPS=1 npm_config_nodedir=/usr/local \
154
+ NODE_PATH=/tmp/sharp-build/node_modules PATH="/tmp/sharp-build/node_modules/.bin:$PATH" \
155
+ node install/build.js; \
156
+ addon="sharp-linuxmusl-$(node -p "process.arch")-${version}.node"; \
157
+ test -f "src/build/Release/${addon}"; \
158
+ mkdir -p /opt/sharp-addon; \
159
+ cp "src/build/Release/${addon}" /opt/sharp-addon/; \
160
+ rm -rf src/build /tmp/sharp-build; \
161
+ mkdir -p src/build/Release; \
162
+ cp "/opt/sharp-addon/${addon}" src/build/Release/
163
+
43
164
  # ===================================================================
44
- # Stage 2: Build (compile TypeScript)
165
+ # Stage 3: Build (compile TypeScript)
45
166
  # ===================================================================
46
- FROM node:20-alpine@sha256:fb4cd12c85ee03686f6af5362a0b0d56d50c58a04632e6c0fb8363f609372293 AS builder
167
+ # Independent of stages 1-2 (tsc and prisma generate never load sharp), so
168
+ # BuildKit runs it in parallel with the libvips compile.
169
+ FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS builder
47
170
 
48
171
  # Override NODE_ENV to ensure devDependencies are installed.
49
172
  # Coolify may inject NODE_ENV=production as a build arg, which causes npm ci
@@ -74,12 +197,29 @@ RUN npx prisma generate
74
197
  RUN npm run build
75
198
 
76
199
  # ===================================================================
77
- # Stage 3: Production Runtime
200
+ # Stage 4: Production Runtime
78
201
  # ===================================================================
79
- FROM node:20-alpine@sha256:fb4cd12c85ee03686f6af5362a0b0d56d50c58a04632e6c0fb8363f609372293 AS production
202
+ FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS production
203
+
204
+ # dumb-init: proper signal handling.
205
+ # curl: Coolify's own HTTP health check runs curl (then BusyBox wget) inside
206
+ # the container. Without curl it falls back to wget, which tries only the
207
+ # first address `localhost` resolves to (often IPv6 ::1, while the app
208
+ # listens on IPv4), so Coolify marks a healthy app unhealthy and rolls the
209
+ # deploy back. curl tries both addresses.
210
+ # The rest are the shared libraries our libvips links against (one per -dev
211
+ # package in stage 1). Alpine ships WebP's mux/demux libraries separately from
212
+ # libwebp and sharp fails to load without them; the libheif plugins decode
213
+ # HEIC (libde265) and AVIF (aom).
214
+ RUN apk add --no-cache \
215
+ dumb-init curl \
216
+ glib expat libjpeg-turbo libpng libwebp libwebpmux libwebpdemux \
217
+ tiff lcms2 libheif libheif-libde265 libheif-aom libexif
80
218
 
81
- # Install dumb-init for proper signal handling
82
- RUN apk add --no-cache dumb-init
219
+ # The libvips built in stage 1. sharp's addon links to it without an rpath,
220
+ # so the dynamic loader is told where it lives.
221
+ COPY --from=libvips /opt/vips/lib /opt/vips/lib
222
+ ENV LD_LIBRARY_PATH=/opt/vips/lib
83
223
 
84
224
  # Create non-root user for security
85
225
  RUN addgroup -g 1001 -S nodejs && \
@@ -87,9 +227,15 @@ RUN addgroup -g 1001 -S nodejs && \
87
227
 
88
228
  WORKDIR /app
89
229
 
230
+ # Pin production mode in the runtime image. src/config/env.ts already defaults
231
+ # an unset NODE_ENV to production; this keeps the image fail-closed even if that
232
+ # default ever changes. A runtime NODE_ENV from Coolify still overrides it.
233
+ ENV NODE_ENV=production
234
+
90
235
  # Copy production dependencies from dependencies stage.
91
- # Includes the Prisma CLI (+ its engines) installed in stage 1, which the
92
- # CMD below needs for `npx prisma migrate deploy`.
236
+ # Includes the Prisma CLI (+ its engines) installed in stage 2, which the
237
+ # CMD below needs for `npx prisma migrate deploy`, and the CPU-safe sharp
238
+ # addon built there.
93
239
  COPY --from=dependencies --chown=nodejs:nodejs /app/node_modules ./node_modules
94
240
 
95
241
  # Copy generated Prisma client from builder stage (not present in prod deps)
@@ -102,6 +248,10 @@ COPY --from=builder --chown=nodejs:nodejs /app/package.json ./package.json
102
248
  # Copy Prisma files (needed for migrations)
103
249
  COPY --from=builder --chown=nodejs:nodejs /app/prisma ./prisma
104
250
 
251
+ # Build-time sharp and HEIC proofs (see each script's header).
252
+ COPY --chown=nodejs:nodejs scripts/check-sharp.mjs ./scripts/check-sharp.mjs
253
+ COPY --chown=nodejs:nodejs scripts/check-heic.mjs ./scripts/check-heic.mjs
254
+
105
255
  # Create BOTH upload tiers with correct ownership (must be before USER nodejs).
106
256
  # public/ is served as static files at /uploads/; private/ is served ONLY via
107
257
  # the auth-gated route GET /api/v1/files/:filename. See file-storage.service.ts.
@@ -110,15 +260,25 @@ RUN mkdir -p /app/uploads/public /app/uploads/private && chown -R nodejs:nodejs
110
260
  # Switch to non-root user
111
261
  USER nodejs
112
262
 
263
+ # Prove sharp loads our addon and converts images in THIS image, as the
264
+ # runtime user, before the image can ship. A failure fails the build instead
265
+ # of crashing the server on its first upload or at start.
266
+ RUN node scripts/check-sharp.mjs
267
+ # The avatar upload accepts iPhone HEIC photos: prove a real HEVC-coded HEIC
268
+ # decodes here (the HEIF flag check-sharp sees is also true for AVIF-only builds).
269
+ RUN node scripts/check-heic.mjs
270
+
113
271
  # Expose port (matches default PORT in env.ts; override via PORT env var)
114
272
  EXPOSE 8000
115
273
 
116
274
  # Health check for container orchestration.
275
+ # 127.0.0.1, never localhost: the server listens on IPv4 (HOST=0.0.0.0), and
276
+ # localhost can resolve to IPv6 ::1 first, which would refuse the probe.
117
277
  # start-period is 60s because CMD runs `prisma migrate deploy` BEFORE the server
118
278
  # starts listening — a slow migration must not be counted as unhealthy, or
119
279
  # Coolify restart-loops the container mid-migration.
120
280
  HEALTHCHECK --interval=30s --timeout=3s --start-period=60s --retries=3 \
121
- CMD node -e "const p=process.env.PORT||8000;require('http').get('http://localhost:'+p+'/api/v1/live',(r)=>{process.exit(r.statusCode===200?0:1)})"
281
+ CMD node -e "const p=process.env.PORT||8000;require('http').get('http://127.0.0.1:'+p+'/api/v1/live',(r)=>{process.exit(r.statusCode===200?0:1)})"
122
282
 
123
283
  # Use dumb-init to handle signals properly
124
284
  ENTRYPOINT ["dumb-init", "--"]
@@ -128,7 +288,14 @@ ENTRYPOINT ["dumb-init", "--"]
128
288
  # (it isn't from CI, which is why migrations belong here and not in a workflow).
129
289
  # `migrate deploy` is idempotent: it applies only pending migrations and exits 0
130
290
  # when there is nothing to do. Requirements, all satisfied above:
131
- # - prisma CLI in ./node_modules (installed in stage 1, copied with node_modules)
291
+ # - prisma CLI in ./node_modules (installed in stage 2, copied with node_modules)
132
292
  # - ./prisma/schema.prisma + ./prisma/migrations (copied from builder)
293
+ # Refuses to start when the image holds NO migration at all (prisma/migrations
294
+ # deleted, never committed, or the project switched to `db push`): `migrate
295
+ # deploy` would then succeed with nothing to apply and the server would boot
296
+ # healthy on a database without tables, failing only at the first real query.
297
+ # Exiting instead fails the Coolify deploy with this message in the logs, and
298
+ # the previous version keeps serving. New projects ship 0_init, so this only
299
+ # fires when that safety net was removed.
133
300
  # `exec` replaces the shell so node receives signals from dumb-init directly.
134
- CMD ["sh", "-c", "npx prisma migrate deploy && exec node dist/server.js"]
301
+ CMD ["sh", "-c", "if ! ls prisma/migrations/*/migration.sql >/dev/null 2>&1; then echo 'Refusing to start: no Prisma migrations in this image (prisma/migrations/*/migration.sql), so the database would have no tables. Create them with npm run prisma:migrate:dev and commit prisma/migrations.' >&2; exit 1; fi; npx prisma migrate deploy && exec node dist/server.js"]
@@ -14,7 +14,9 @@ name: {{PROJECT_NAME}}
14
14
 
15
15
  services:
16
16
  mysql:
17
- image: mysql:8.0
17
+ # 8.4 is MySQL's long-term release (8.0 reached end of life in April 2026);
18
+ # keep it on the version production runs, so local behaves the same.
19
+ image: mysql:8.4
18
20
  container_name: {{PROJECT_NAME}}-mysql
19
21
  restart: unless-stopped
20
22
  # Local-dev resource bounds. mem_limit is a cgroup ceiling (a runaway container is
@@ -26,7 +28,7 @@ services:
26
28
  - --innodb-buffer-pool-size=128M # default is fine for dev; keeps RSS small
27
29
  - --performance-schema=OFF # saves ~hundreds of MB on its own
28
30
  - --skip-name-resolve # no reverse-DNS per connection (faster, leaner)
29
- - --max-connections=60 # well above DATABASE_POOL_MAX (10) + headroom
31
+ - --max-connections=60 # well above Prisma's pool (connection_limit in DATABASE_URL) + headroom
30
32
  - --innodb-flush-log-at-trx-commit=2 # dev durability/throughput trade — not for prod
31
33
  ports:
32
34
  - '127.0.0.1:${MYSQL_PORT:-{{MYSQL_PORT}}}:3306'
@@ -0,0 +1,63 @@
1
+ # Deploying
2
+
3
+ The server and the client deploy as two Coolify applications from their own Dockerfiles. The setup checklist is in
4
+ the main README ("Deploying to Coolify"); this page explains what a deploy does and the rules that follow from it.
5
+
6
+ ## What a deploy does
7
+
8
+ 1. Coolify builds the image. The server's build compiles libvips (see "Build time" below), installs the exact
9
+ lockfile, builds the code and proves that sharp works in the final image.
10
+ 2. Coolify starts a **new** container next to the one that is serving. Its start command:
11
+ - refuses to start when the image has no Prisma migrations;
12
+ - runs `prisma migrate deploy`, which applies the migrations the database does not have yet. A database it cannot
13
+ reach stops the start here;
14
+ - starts the server. In production the server also refuses to start when it cannot reach Redis within 10 s.
15
+ 3. Coolify waits for the image's Docker `HEALTHCHECK` (server: `/api/v1/live`, client: `/healthz`), then sends traffic
16
+ to the new container and stops the old one. The server finishes its in-flight requests and closes within 8 s
17
+ (Docker's limit is 10 s).
18
+
19
+ If the new container never becomes healthy (a failed migration, no Redis, a crash), Coolify keeps the old container
20
+ serving, and the deploy shows as failed.
21
+
22
+ ## Migrations: expand, deploy, contract
23
+
24
+ Between steps 2 and 3 the **old** code runs against the **new** schema, and nothing can roll a migration back: a
25
+ redeploy of an older commit only runs `migrate deploy` again, which moves forward. So every migration must work with
26
+ the code that is still running:
27
+
28
+ 1. **Expand.** Add tables, columns (nullable or with a default) and indexes. Deploy.
29
+ 2. **Move the code** to the new shape, and backfill data if needed. Deploy.
30
+ 3. **Contract**, in a later deploy: drop or rename only what no running code uses any more.
31
+
32
+ Never in the same deploy as the code that stops using it:
33
+
34
+ - drop a column or a table;
35
+ - rename one: Prisma writes a rename as drop + add, losing the data unless you edit the migration. To rename only in
36
+ the code, keep the database name with `@map` / `@@map`;
37
+ - change a column's type, or make it required without a default.
38
+
39
+ The old container would read or write the old shape for the length of the switch and fail.
40
+
41
+ Before a risky migration, back up the database (on Coolify: the database's Backups tab, run a backup now). To undo
42
+ one, write a new forward migration, or restore the backup, losing what was written since.
43
+
44
+ ## Rolling back the code
45
+
46
+ Redeploy the previous commit, or use Coolify's rollback on the Deployments tab. That is safe as long as the schema
47
+ still suits the old code, which is what expand / deploy / contract guarantees.
48
+
49
+ ## Build time: libvips
50
+
51
+ Both images compile libvips, the image library behind sharp, from source. sharp's prebuilt binaries need x86-64-v2
52
+ CPU features that some VPS CPUs lack; the images build libvips for baseline x86-64, so they run on any x86-64 server.
53
+
54
+ Uncached, the compile takes about 6 to 7 minutes of the server's CPU per application (measured on a shared VPS:
55
+ 6.2 to 6.6 minutes, about 8.5 minutes for the whole server deploy), and other apps on the same server can slow down
56
+ meanwhile. Docker keeps the compiled stage in that server's build cache, and a later deploy that reuses it finishes
57
+ in 1 to 2 minutes. Expect the long build on the first deploy of each application to a server (the two do not share
58
+ it on Coolify), after a change to a build-time variable (the client's `NEXT_PUBLIC_*` values), after the server's
59
+ build cache was cleaned up, and when the base image or `LIBVIPS_VERSION` changes. Other deploys may hit the cache,
60
+ but do not count on it.
61
+
62
+ The fix for later: build the libvips stage once into a base image in a registry (it needs CI to publish it) and
63
+ start both Dockerfiles from it. Until then, deploy when the server is quiet if its other apps are sensitive to load.
@@ -2,20 +2,46 @@
2
2
 
3
3
  ## Overview
4
4
 
5
- The server uses a single-line request/response logging system built on Pino, providing color-coded, informative logs for every API request.
5
+ The server uses a single-line request/response logging system built on Pino, providing informative logs for every API request, color-coded in a development terminal.
6
6
 
7
7
  ## Log Format
8
8
 
9
9
  Each completed request produces a single log line:
10
10
 
11
11
  ```
12
- GET /api/v1/auth/me 200 OK (12ms)
12
+ GET /api/v1/auth/me 200 OK (12ms) [ip=203.0.113.7 reqId=<uuid>]
13
13
  ```
14
14
 
15
- Format: `METHOD URL STATUS STATUS_MESSAGE (DURATION)`
15
+ Format: `METHOD PATH STATUS STATUS_MESSAGE (DURATION) [ip=CLIENT_IP reqId=REQUEST_ID]`
16
+
17
+ `PATH` is the URL without its query string or fragment: queries carry search terms and email
18
+ addresses (`/admin/users?search=jane@example.com`), and links from emails carry tokens, so no
19
+ request log keeps them. Route params (ids) stay.
20
+
21
+ In production (JSON logs) the same parts are also separate fields on the line, so log search can
22
+ filter on them instead of parsing `msg`:
23
+
24
+ ```json
25
+ {"level":30,"time":1760918400000,"reqId":"<uuid>","method":"GET","path":"/api/v1/auth/me","statusCode":200,"durationMs":12,"ip":"203.0.113.7","msg":"GET /api/v1/auth/me 200 OK (12ms) [ip=203.0.113.7 reqId=<uuid>]"}
26
+ ```
27
+
28
+ | Field | Meaning |
29
+ |---|---|
30
+ | `reqId` | the request id (also the `x-request-id` response header) |
31
+ | `method` | HTTP method |
32
+ | `path` | URL without query or fragment |
33
+ | `statusCode` | response status |
34
+ | `durationMs` | time from the route's preHandler to the response, in ms |
35
+ | `ip` | resolved client IP (Cloudflare or proxy aware, `src/libs/client-ip.ts`) |
36
+
37
+ Development logs (pino-pretty) show only the line, without the field list under it.
38
+
39
+ `REQUEST_ID` is also sent back as the `x-request-id` response header. An inbound `X-Request-Id` (from a proxy in front) is kept only when it is at most 128 letters, digits, `.`, `_` or `-`; anything else gets a fresh UUID (`src/libs/request-id.ts`).
16
40
 
17
41
  ## Color Coding
18
42
 
43
+ Colors are added only when stdout is a terminal and `NODE_ENV` is not `production` (`shouldColorize()` in `src/libs/requestLogger.ts`). Production and container logs are plain text: escape codes would otherwise show up as `\u001b[34m` junk inside the JSON `msg` field.
44
+
19
45
  ### HTTP Methods (ANSI colors)
20
46
  - **Blue**: GET (read operations)
21
47
  - **Green**: POST (create operations)
@@ -44,6 +70,28 @@ Health check endpoints are excluded from logging to reduce noise:
44
70
  - `/api/v1/ready`
45
71
  - `/api/v1/live`
46
72
 
73
+ ## Health checks
74
+
75
+ Public, never rate limited or IP-blocked (`src/libs/health-routes.ts`):
76
+
77
+ | Route | Answer | Use |
78
+ |---|---|---|
79
+ | `GET /api/v1/health` | `{ status }`: `healthy` / `degraded` → 200, `unhealthy` → 503 | uptime monitors |
80
+ | `GET /api/v1/ready` | `{ ready, timestamp }`, 503 while the database is down | load balancers |
81
+ | `GET /api/v1/live` | `{ alive, timestamp }` | the Docker `HEALTHCHECK` |
82
+
83
+ `unhealthy` means the database is down. `degraded` means the database is slow (100 ms or more),
84
+ Redis is down or slow (so rate limits and IP blocks are off), or the heap is above 85% of its limit.
85
+
86
+ The public answer never says which check failed. Admins get the full report at
87
+ `GET /api/v1/admin/health`: per check status and timing, memory (heap used and limit, RSS),
88
+ uptime, `checkedAt`, `version` (from `package.json`) and `commit` (`SOURCE_COMMIT`, which
89
+ Coolify sets).
90
+
91
+ The database and Redis are checked at most once per 5 s; every probe in between gets the same
92
+ answer (`checkedAt` says when it was taken). A failing check logs the error at `error`
93
+ (database) or `warn` (Redis).
94
+
47
95
  ## Configuration
48
96
 
49
97
  ### Development
@@ -51,7 +99,7 @@ Health check endpoints are excluded from logging to reduce noise:
51
99
  - Set `LOG_LEVEL=debug` in `.env` for verbose output
52
100
 
53
101
  ### Production
54
- - Uses structured JSON logs (Pino default)
102
+ - Uses structured JSON logs (Pino default), with no color codes
55
103
  - Optimized for log aggregation tools (ELK, CloudWatch, Datadog)
56
104
  - Set `LOG_LEVEL=info` or `LOG_LEVEL=warn` in `.env`
57
105
 
@@ -0,0 +1,153 @@
1
+ # Rate limits, login lockout and IP blocks
2
+
3
+ Everything that slows down or stops a visitor, in one place. The limits themselves live in `src/config/rate-limit.config.ts`, the single source; the wiring is in `src/libs/rate-limiting.ts`.
4
+
5
+ ## How counting works
6
+
7
+ - **Per visitor IP.** The key is the verified client IP (`getClientIp`, see `src/libs/client-ip.ts`), never an address the visitor wrote into a header.
8
+ - **Per route.** Every route keeps its own counter, even when two routes share a limit entry.
9
+ - **Shared across server processes.** Counters live in Redis.
10
+ - **Every "slow down" answer says how long to wait** in `retryAfterSeconds` (whole seconds) inside the JSON body. The client runs on another origin and CORS does not expose the `Retry-After` header to it.
11
+
12
+ ## Route limits
13
+
14
+ | Route | Limit (per IP) | Name |
15
+ |---|---|---|
16
+ | `POST /auth/register` | 40 per hour | `AUTH_REGISTER` |
17
+ | `POST /auth/login` | 100 per 15 min | `AUTH_LOGIN` |
18
+ | `POST /auth/logout` | 200 per 15 min | `AUTH_LOGOUT` |
19
+ | `POST /auth/refresh` | 200 per 15 min | `AUTH_REFRESH` |
20
+ | `POST /auth/forgot-password` | 20 per 15 min (+ email cap) | `AUTH_FORGOT_PASSWORD` |
21
+ | `POST /auth/reset-password` | 100 per 15 min | `AUTH_RESET_PASSWORD` |
22
+ | `GET /auth/me` | 200 per minute | `AUTH_ME` |
23
+ | `GET /auth/sessions` | 30 per minute | `AUTH_SESSIONS` |
24
+ | `POST /auth/logout-all` | 10 per 15 min | `AUTH_LOGOUT_ALL` |
25
+ | `POST /auth/send-verification` (email module) | 10 per 15 min (+ email cap) | `AUTH_SEND_VERIFICATION` |
26
+ | `POST /auth/verify-account` (email module) | 10 per 15 min | `AUTH_VERIFY_ACCOUNT` |
27
+ | `PATCH /users/me`, `PATCH /users/:userId` | 30 per minute | `USERS_UPDATE_PROFILE` |
28
+ | `PATCH /users/me/password`, `PATCH /users/:userId/password` | 10 per 15 min | `USERS_CHANGE_PASSWORD` |
29
+ | `DELETE /users/me`, `DELETE /users/:userId` | 10 per minute | `USERS_DELETE_ACCOUNT` |
30
+ | `POST /users/avatar`, `POST /users/:userId/avatar` | 10 per minute | `USERS_UPLOAD_AVATAR` |
31
+ | `DELETE /users/avatar`, `DELETE /users/:userId/avatar` | 30 per minute | `USERS_DELETE_AVATAR` |
32
+ | `GET /files/:filename` | 100 per minute | `FILES_GET` |
33
+ | every `/admin/*` route | 30 per minute | `ADMIN_DEFAULT` |
34
+ | **any other route** (including routes you add) | 200 per minute | `DEFAULT` |
35
+ | unknown URLs (404s) | 200 per minute, one shared counter | `DEFAULT` |
36
+
37
+ All paths are under `/api/v1`. Password change checks the current password, so it stays low: someone holding a stolen session cannot guess that password. An avatar upload decodes an image of up to 50 MP, which is real CPU work.
38
+
39
+ **Never limited:**
40
+ - `GET /api/v1/health`, `/api/v1/ready` and `/api/v1/live` (health probes come from infrastructure IPs);
41
+ - static `/uploads/*` (one page can load dozens of avatars);
42
+ - CORS preflights (`OPTIONS`).
43
+
44
+ A new route gets `DEFAULT` automatically. Give it its own entry in `RATE_LIMITS` and `config: { rateLimit: RATE_LIMITS.MY_ROUTE }` when it needs a different number.
45
+
46
+ ## Email cap
47
+
48
+ At most **3 emails per hour to one address**, on two separate counters so a stranger can never use up the owner's emails:
49
+
50
+ | Counter | Emails it covers | Over the cap |
51
+ |---|---|---|
52
+ | public | forgot-password, send-verification (anyone can type an address) | `429 EMAIL_RATE_LIMITED` with the wait time |
53
+ | sign-in | the verification link re-sent when an unverified user signs in with the **right password** | email skipped and logged; the user is still told to verify |
54
+
55
+ - **Not counted at all:** the single verification email sent at register. An address can register only once, so it cannot flood anyone, and strangers who used up the public counter cannot stop it.
56
+ - Why the sign-in re-send is still capped: whoever registered an address knows its password and could otherwise flood that inbox by signing in again and again.
57
+ - Both counters are charged **before** looking the account up, so unknown addresses count exactly like real ones and the answer reveals nothing.
58
+ - Redis keys are a SHA-256 of the address; raw emails are never stored there.
59
+
60
+ The IP limits alone cannot do this: someone with many IPs could flood one inbox and burn the sender's quota and reputation.
61
+
62
+ ## Login lockout
63
+
64
+ This is separate from the route limits, and counted per **email + IP pair**. An attacker therefore only locks out their own address and can never lock the real user out remotely.
65
+
66
+ - The 15th failed sign-in locks that pair for **15 minutes**.
67
+ - The 30th failure (and every 15th after it) locks it for **1 hour**.
68
+ - The failure count is forgotten an hour after the last failure, and a successful sign-in clears it.
69
+ - While locked, every attempt, even with the right password, gets `429 LOGIN_LOCKED`: "Too many failed sign-in attempts. Try again in N minutes."
70
+ - Unknown emails are counted and locked the same way and take the same password-check time (a dummy hash). Neither the lock nor the timing reveals which emails are registered.
71
+ - A wrong password outside a lock still says "Invalid email or password".
72
+
73
+ ## IP auto-block
74
+
75
+ - Every request **over a limit** on a non-auth route records one strike against the IP. Requests to `/api/v1/auth/*` add no strikes, so a mistyped password can never ban a whole network.
76
+ - `IP_AUTO_BLOCK_THRESHOLD` strikes (default 20) within `IP_AUTO_BLOCK_WINDOW_SECONDS` (default 300) block the IP on **every** route for `IP_AUTO_BLOCK_DURATION_SECONDS` (default 3600). The answer is `403 IP_BLOCKED` with `retryAfterSeconds`.
77
+ - Private, loopback and reserved addresses (your own proxy) are never auto-blocked. Health probes are never blocked.
78
+ - Admins can add permanent blocks (`/admin/blocked-ips`). Those answer `403 IP_BLOCKED` "Access from your network is blocked." with no wait time.
79
+
80
+ Before you shorten a window, read the note at the top of `rate-limit.config.ts`. A client that keeps hammering a short-window route after its 429 bans itself within minutes.
81
+
82
+ ## Response shape
83
+
84
+ ```json
85
+ { "success": false, "error": { "code": "LOGIN_LOCKED", "message": "Too many failed sign-in attempts. Try again in 14 minutes.", "retryAfterSeconds": 840 } }
86
+ ```
87
+
88
+ | Code | Status | When |
89
+ |---|---|---|
90
+ | `RATE_LIMIT_EXCEEDED` | 429 | a route limit (or the default) was exceeded |
91
+ | `LOGIN_LOCKED` | 429 | too many failed sign-ins for this email + IP |
92
+ | `EMAIL_RATE_LIMITED` | 429 | too many emails to this address this hour |
93
+ | `IP_BLOCKED` | 403 | the IP is auto-blocked (`retryAfterSeconds` set) or permanently blocked (not set) |
94
+
95
+ **The client** (`client/src/lib/api/axios.config.ts`):
96
+ - It shows one toast with the wait time for these codes.
97
+ - The login, register and forgot-password forms show the message inline instead.
98
+ - React Query never retries these answers, because a retry would only earn another strike.
99
+ - A limited `/auth/refresh` never logs the user out.
100
+
101
+ ## Changing limits (ENV)
102
+
103
+ | Variable | Default | Meaning |
104
+ |---|---|---|
105
+ | `RATE_LIMIT_ENABLED` | `true` | Master switch. `false` makes every limit 1,000,000 (the email cap too). |
106
+ | `RATE_LIMIT_MULTIPLIER` | `1` | Scales every max, e.g. `10` for local development. |
107
+ | `RATE_LIMIT_OVERRIDES` | (empty) | Change single limits: `NAME=MAX/WINDOW,...` with `WINDOW` like `30s`, `15m` or `1h`. |
108
+
109
+ Example: `RATE_LIMIT_OVERRIDES=AUTH_LOGIN=200/15m,DEFAULT=300/1m,EMAIL_PER_ADDRESS=5/1h`
110
+
111
+ - `NAME` is any name from the table above (`RATE_LIMITS` keys), `DEFAULT` or `EMAIL_PER_ADDRESS`.
112
+ - An override replaces that limit's max and window; the multiplier still applies on top.
113
+ - An unknown name or a malformed value stops the server at boot with the list of valid names, so a typo never goes unnoticed.
114
+ - The old `RATE_LIMIT_AUTH_LOGIN_MAX` and `RATE_LIMIT_AUTH_REGISTER_MAX` are no longer read. If one is still set, the server logs a warning at boot and ignores it.
115
+
116
+ ## When Redis is down
117
+
118
+ The app keeps serving, but while Redis is unreachable:
119
+ - rate limits, the email cap and the login lockout are off;
120
+ - IP blocks are not enforced;
121
+ - forgot-password, reset-password, send-verification and verify-account answer `503 SERVICE_UNAVAILABLE` ("Password reset is temporarily unavailable. Please try again in a few minutes."). Their tokens live in Redis, so they cannot work. The check runs before any account lookup, so the answer is the same for every address and reveals nothing (`src/libs/redis-required.ts`).
122
+
123
+ `/api/v1/health` reports `degraded`; admins see that it is Redis at `/api/v1/admin/health`. Everything returns on its own when Redis is back; permanent blocks are re-loaded from the database on reconnect.
124
+
125
+ A missing or unreachable `REDIS_URL` at boot is different from an outage: in production the server refuses to start without it, and also when it cannot reach Redis within 10 s of starting (a wrong host or password), because it would otherwise run with every protection above switched off while its health check still passes. On Coolify that failed start never becomes healthy, so a rolling deploy keeps the old container serving. Outside production it defaults to `redis://localhost:6379` and starts without Redis.
126
+
127
+ ## Behind Cloudflare
128
+
129
+ Cloudflare requests that cannot be verified as your own zone's traffic share **one** counter. This happens in two cases:
130
+ - an origin secret is set without its Transform Rule;
131
+ - the traffic comes through a Cloudflare Worker.
132
+
133
+ On a correct setup this never happens. The server logs `[CLIENT-IP] Cloudflare requests ... share one rate-limit bucket` (at most every 10 minutes) when it does. See `docs/client-ip-behind-proxies.md` in the create-tigra repository.
134
+
135
+ ## Known limits (read before relying on these)
136
+
137
+ - **Anyone can use up an address's public email counter.** Three anonymous forgot-password or send-verification requests in an hour use up that address's public counter. For the rest of the hour nobody gets a reset link through that address. A determined stranger can keep doing this every hour, keeping one person from resetting a password by email. Verification is **not** blocked: the register email is not capped, and signing in with the right password re-sends the link on its own counter. A user who knows their password is not affected.
138
+ - **Whether an email has an account can be found out.** Sign-up answers `409 EMAIL_ALREADY_EXISTS` for an existing account (and for one deleted recently, while its email stays reserved), and forgot-password gives the same answer for every address but takes noticeably longer for a real account, because it sends the email before replying. This is accepted on purpose (most apps do the same, and hiding it would make sign-up confusing). Sign-in and the lockout still reveal nothing: unknown emails cost the same time and lock the same way.
139
+ - **An unverified sign-up keeps its email.** With email verification on, someone can sign up with another person's address and never verify it. The real owner then gets `409 EMAIL_ALREADY_EXISTS` when signing up. They are not locked out: "forgot password" sends the reset link to their own inbox, and after resetting, signing in sends them the verification link. Accounts are never deleted automatically for staying unverified.
140
+ - **Parallel sign-in attempts can get ahead of the lockout.** A burst of simultaneous failed sign-ins from one IP is checked before any of them is counted, so it can try more than 15 passwords. It is still capped by the login route limit (100 per 15 minutes per IP).
141
+ - **`HEAD` requests count separately from `GET`.** Fastify adds a `HEAD` route for each `GET`, and it gets its own counter.
142
+ - **IP blocks are single addresses.** An IPv6 visitor usually controls a whole /64 network and can switch to another address in it, so blocking one IPv6 address only slows such a visitor down. Ranges (CIDR) are not supported. Blocks are stored in one canonical spelling, so `2001:DB8::1` and `2001:0db8:0:0::1` are the same block. An admin cannot block their own current address, nor a private or reserved one.
143
+
144
+ ## Porting to an app made with an older create-tigra
145
+
146
+ 1. Copy `src/config/rate-limit.config.ts`, `src/libs/rate-limiting.ts` and `src/libs/email-quota.ts`. Then copy the `app.ts` changes (`registerRateLimiting`, `registerNotFoundHandler`, `rateLimit: false` on the health routes, `getIpBlock`), `TooManyRequestsError` and `retryAfterSeconds` in `shared/errors`, `errorResponse`, and the auth-service lockout.
147
+ 2. Replace `RATE_LIMIT_AUTH_LOGIN_MAX` / `RATE_LIMIT_AUTH_REGISTER_MAX` in every environment with `RATE_LIMIT_OVERRIDES`, for example `AUTH_LOGIN=100/15m`. Remember that the old variables are now ignored.
148
+ 3. Drop the two dead lockout columns with a migration. Nothing reads them any more:
149
+ ```sql
150
+ ALTER TABLE `users` DROP COLUMN `failedLoginAttempts`, DROP COLUMN `lockedUntil`;
151
+ ```
152
+ These are the template's column names (the fields have no `@map`). Or remove `failedLoginAttempts` and `lockedUntil` from the `User` model and let `prisma migrate dev` generate the migration.
153
+ 4. Client: copy `getLimitInfo` / `isLimitError` / `formatWait` (`lib/utils/error.ts`), the interceptor branch and the refresh check (`lib/api/axios.config.ts`), the `retry` function (`app/providers.tsx`), `LimitNotice` and the form changes.