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,77 +1,158 @@
1
- /**
2
- * Client IP resolution — Cloudflare- and reverse-proxy-aware.
3
- *
4
- * Behind a Cloudflare proxy (or any reverse proxy such as Traefik/Coolify),
5
- * Fastify's `request.ip` (derived from the socket / X-Forwarded-For) resolves
6
- * to an *edge* IP, not the real visitor. Every request through one edge node
7
- * then shares a single IP, which collapses the per-IP rate limiter and the IP
8
- * auto-block onto that shared edge address: one abusive client can rate-limit
9
- * or self-ban every legitimate user behind the same edge, and conversely abuse
10
- * from many clients hides behind one IP.
11
- *
12
- * Resolution is ordered, and every header value is VALIDATED as a real IPv4/IPv6
13
- * literal (via `node:net.isIP`) before it is trusted — a junk or spoofed header
14
- * falls through to the next tier instead of becoming the rate-limit key:
15
- *
16
- * 1. `CF-Connecting-IP` — the genuine client IP Cloudflare injects. Consulted
17
- * ONLY when `TRUST_CLOUDFLARE` is enabled (orange-cloud / proxied origin).
18
- * 2. Left-most VALID `X-Forwarded-For` entry — the original client, appended by
19
- * the reverse proxy. XFF is a comma-separated list (client, proxy1, proxy2,
20
- * ...), so the original client is the left-most entry. This tier is consulted
21
- * regardless of the flag: it covers the grey-cloud / DNS-only case where the
22
- * Cloudflare header is absent but traffic still arrives through Traefik —
23
- * without it, every grey-clouded visitor collapses onto the single shared
24
- * Traefik upstream IP and trips the auto-block site-wide.
25
- * 3. `request.ip` — Fastify's socket / trustProxy-resolved peer IP (always
26
- * non-empty), the safe fallback for any origin reachable directly.
27
- *
28
- * SECURITY PRECONDITION: both `CF-Connecting-IP` and `X-Forwarded-For` are
29
- * client-supplied and therefore SPOOFABLE if a caller can reach the origin
30
- * directly. They are only trustworthy when the origin accepts traffic
31
- * EXCLUSIVELY via the proxy (Cloudflare / Traefik) — a documented deploy
32
- * precondition. Validation here narrows the spoof surface to well-formed IP
33
- * literals but does not, on its own, prove provenance.
34
- *
35
- * Use this for rate-limiting and IP-blocking decisions. Logging / session
36
- * metadata can keep using `request.ip` — there a spoofed value is harmless.
37
- */
38
-
39
- import { isIP } from 'node:net';
40
- import type { FastifyRequest } from 'fastify';
41
- import { env } from '@config/env.js';
42
-
43
- /** Return the trimmed value if it is a valid IPv4/IPv6 literal, else undefined. */
44
- function asValidIp(value: string | undefined): string | undefined {
45
- if (!value) return undefined;
46
- const trimmed = value.trim();
47
- return isIP(trimmed) !== 0 ? trimmed : undefined;
48
- }
49
-
50
- /**
51
- * Resolve the real client IP for rate-limiting / blocking decisions.
52
- *
53
- * Synchronous and always returns a non-empty string (the `request.ip` fallback
54
- * guarantees this), so it is safe to use directly as a rate-limit `keyGenerator`.
55
- *
56
- * @param request - The incoming Fastify request
57
- * @returns The client IP to use as the rate-limit / block key
58
- */
59
- export function getClientIp(request: FastifyRequest): string {
60
- // 1. CF-Connecting-IP — only when TRUST_CLOUDFLARE is set (origin locked to CF).
61
- if (env.TRUST_CLOUDFLARE) {
62
- const cfHeader = request.headers['cf-connecting-ip'];
63
- const cf = asValidIp(typeof cfHeader === 'string' ? cfHeader : undefined);
64
- if (cf) return cf;
65
- }
66
- // 2. Left-most VALID X-Forwarded-For entry — the original client, appended by the
67
- // reverse proxy (Traefik/Coolify). Covers grey-cloud / DNS-only where the CF
68
- // header is absent. Validated so a junk/spoofed header falls through.
69
- const xffRaw = request.headers['x-forwarded-for'];
70
- const xff = typeof xffRaw === 'string' ? xffRaw : Array.isArray(xffRaw) ? xffRaw[0] : undefined;
71
- if (xff) {
72
- const leftMost = asValidIp(xff.split(',')[0]);
73
- if (leftMost) return leftMost;
74
- }
75
- // 3. Fastify's socket/trustProxy-resolved peer IP (always non-empty).
76
- return request.ip;
77
- }
1
+ /**
2
+ * Client IP resolution: verify before believing.
3
+ *
4
+ * Every per-visitor protection keys on this address: the rate limiter, the login lockout
5
+ * (email + IP), the IP auto-block and the manual block list, plus session records and access
6
+ * logs. Two failure modes have to be avoided at the same time:
7
+ *
8
+ * 1. SHARED COUNTERS. Behind Cloudflare and Coolify's Traefik, the TCP peer is the proxy, so
9
+ * using the socket address alone counts every visitor as one: a handful of users trip the
10
+ * limits together and lock each other out (this happened on real sites).
11
+ * 2. FORGED ADDRESSES. `X-Forwarded-For` and `CF-Connecting-IP` are request headers the
12
+ * visitor can write. The previous version believed the LEFT-most X-Forwarded-For entry
13
+ * (written by the visitor) and believed CF-Connecting-IP from anyone when TRUST_CLOUDFLARE
14
+ * was on, so a client could pick its own key: dodge rate limits and lockouts, or get
15
+ * somebody else's address banned.
16
+ *
17
+ * How the address is chosen now:
18
+ *
19
+ * - Fastify's `trustProxy` is set to TRUSTED_PROXY_RANGES (loopback, link-local and private
20
+ * networks). Coolify's Traefik reaches the app from a private Docker-network address, so it
21
+ * is trusted; anyone on the public internet is not. `request.ip` is then the right-most
22
+ * UNTRUSTED hop: the address our own proxy saw connecting to it. Entries a visitor writes
23
+ * into X-Forwarded-For sit to the left of that and are never used.
24
+ * - If that address belongs to Cloudflare's edge (cloudflare-ranges.ts), the request came
25
+ * from Cloudflare's network, and CF-Connecting-IP names the visitor, but only once the
26
+ * request is also VERIFIED as genuine traffic of this app's own zone (see below).
27
+ * - Otherwise that address is the visitor (a direct visitor, a grey-cloud domain, sslip.io).
28
+ *
29
+ * Why Cloudflare's ranges alone are not proof: they are shared by every Cloudflare customer.
30
+ * A Cloudflare Worker (free for anyone) that fetches one of this app's NON-Cloudflare addresses
31
+ * (sslip.io, a grey-cloud record, the server IP) leaves from those ranges and may set
32
+ * CF-Connecting-IP to any value (Cloudflare documents this). So a Cloudflare request counts as
33
+ * verified only when:
34
+ * - CLOUDFLARE_ORIGIN_SECRET is set: it carries the matching X-Origin-Verify header, which a
35
+ * Transform Rule on the owner's own zone adds (Cloudflare's recommended origin proof); or
36
+ * - no secret is set: it does not carry the CF-Worker header that Cloudflare adds to Worker
37
+ * subrequests (documented as added; not documented as unremovable, hence the secret).
38
+ * An unverified Cloudflare request is keyed on ONE fixed bucket, never on the address it claims:
39
+ * it can neither pick a fresh key per attempt nor spread across Cloudflare's many edge addresses.
40
+ *
41
+ * TRUST_CLOUDFLARE no longer exists (an old value is ignored). Behind a proxy or CDN other than
42
+ * Cloudflare and Traefik, the result is that proxy's address: counters are then shared, which
43
+ * is strict but cannot be forged. See docs/client-ip-behind-proxies.md.
44
+ */
45
+ import { timingSafeEqual } from 'node:crypto';
46
+ import type { FastifyRequest } from 'fastify';
47
+ import { env } from '@config/env.js';
48
+ import { isCloudflareIp } from '@libs/cloudflare-ranges.js';
49
+ import { normalizeIp } from '@libs/ip-address.js';
50
+ import { logger } from '@libs/logger.js';
51
+
52
+ /** Header the owner's Cloudflare Transform Rule adds (names starting with cf- or x-cf- cannot be set there). */
53
+ export const ORIGIN_VERIFY_HEADER = 'x-origin-verify';
54
+ /** Rate-limit / lockout key shared by every Cloudflare request that could not be verified. */
55
+ export const UNVERIFIED_CLOUDFLARE_KEY = 'cloudflare-unverified';
56
+
57
+ /**
58
+ * Hops whose X-Forwarded-For entries are trusted (proxy-addr keywords): loopback
59
+ * (127.0.0.0/8, ::1), link-local (169.254.0.0/16, fe80::/10) and private networks
60
+ * (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7). Passed to Fastify as `trustProxy`.
61
+ * Cloudflare's ranges are deliberately NOT here: a Cloudflare hop is only believed through
62
+ * CF-Connecting-IP, which Cloudflare itself overwrites.
63
+ */
64
+ export const TRUSTED_PROXY_RANGES = 'loopback,linklocal,uniquelocal';
65
+
66
+ /**
67
+ * Where the resolved address came from: Cloudflare's header on a verified request, a Cloudflare
68
+ * request that could not be verified (fixed bucket), our proxy's record, or the TCP peer.
69
+ */
70
+ export type ClientIpSource = 'cloudflare' | 'cloudflare-unverified' | 'proxy' | 'socket';
71
+
72
+ export interface ResolvedClientIp {
73
+ ip: string;
74
+ source: ClientIpSource;
75
+ }
76
+
77
+ // Every address the resolver returns goes through the one canonical spelling
78
+ // (libs/ip-address.ts), shared with the IP block list. Re-exported for callers.
79
+ export { normalizeIp } from '@libs/ip-address.js';
80
+
81
+ /**
82
+ * Resolve the visitor address and say where it came from. Synchronous and always returns a
83
+ * non-empty address, so it can serve directly as a rate-limit key.
84
+ */
85
+ export function resolveClientIp(request: FastifyRequest): ResolvedClientIp {
86
+ const socketIp = normalizeIp(request.socket?.remoteAddress);
87
+ // request.ip = the right-most untrusted hop (see TRUSTED_PROXY_RANGES); falls back to the
88
+ // raw socket address, then a constant, so a key always exists.
89
+ const peer = normalizeIp(request.ip) ?? socketIp ?? request.ip ?? 'unknown';
90
+
91
+ if (isCloudflareIp(peer)) {
92
+ if (!isVerifiedCloudflareRequest(request)) {
93
+ warnUnverifiedCloudflare();
94
+ return { ip: UNVERIFIED_CLOUDFLARE_KEY, source: 'cloudflare-unverified' };
95
+ }
96
+ const header = request.headers['cf-connecting-ip'];
97
+ const visitor = normalizeIp(typeof header === 'string' ? header : undefined);
98
+ if (visitor) return { ip: visitor, source: 'cloudflare' };
99
+ // A verified Cloudflare request always carries the header; without it, stay on the edge
100
+ // address (strict) rather than guess.
101
+ }
102
+
103
+ return { ip: peer, source: socketIp !== undefined && peer !== socketIp ? 'proxy' : 'socket' };
104
+ }
105
+
106
+ /** At most one warning per this many milliseconds per process (resolveClientIp runs several times per request). */
107
+ export const UNVERIFIED_WARNING_INTERVAL_MS = 10 * 60 * 1000;
108
+ let lastUnverifiedWarningAt = 0;
109
+
110
+ /**
111
+ * Tell the operator that Cloudflare traffic is landing in the shared bucket. On a correctly set
112
+ * up zone this never happens, so it almost always means a misconfiguration that makes all
113
+ * Cloudflare visitors share ONE rate-limit counter. Never logs the secret or header values.
114
+ */
115
+ function warnUnverifiedCloudflare(): void {
116
+ const now = Date.now();
117
+ if (now - lastUnverifiedWarningAt < UNVERIFIED_WARNING_INTERVAL_MS) return;
118
+ lastUnverifiedWarningAt = now;
119
+ logger.warn(
120
+ env.CLOUDFLARE_ORIGIN_SECRET
121
+ ? '[CLIENT-IP] Cloudflare requests without a valid X-Origin-Verify header share one rate-limit bucket. ' +
122
+ 'CLOUDFLARE_ORIGIN_SECRET is set: check that the Transform Rule adding the header exists on this zone. ' +
123
+ 'See docs/client-ip-behind-proxies.md'
124
+ : '[CLIENT-IP] Cloudflare requests carrying a CF-Worker header (Worker traffic) share one rate-limit bucket. ' +
125
+ 'If that traffic is yours, set CLOUDFLARE_ORIGIN_SECRET plus a Transform Rule. See docs/client-ip-behind-proxies.md',
126
+ );
127
+ }
128
+
129
+ /** Test hook: let the next unverified request warn again. */
130
+ export function resetUnverifiedWarningForTests(): void {
131
+ lastUnverifiedWarningAt = 0;
132
+ }
133
+
134
+ /**
135
+ * Whether a request that arrived from Cloudflare's network is genuine traffic of this app's own
136
+ * zone, so its CF-Connecting-IP can be believed (see the module header for why ranges alone are
137
+ * not enough).
138
+ */
139
+ function isVerifiedCloudflareRequest(request: FastifyRequest): boolean {
140
+ const secret = env.CLOUDFLARE_ORIGIN_SECRET;
141
+ if (secret) {
142
+ const presented = request.headers[ORIGIN_VERIFY_HEADER];
143
+ if (typeof presented !== 'string') return false;
144
+ const a = Buffer.from(presented);
145
+ const b = Buffer.from(secret);
146
+ // Constant-time comparison; differing lengths are rejected first (timingSafeEqual throws).
147
+ return a.length === b.length && timingSafeEqual(a, b);
148
+ }
149
+ return request.headers['cf-worker'] === undefined;
150
+ }
151
+
152
+ /**
153
+ * The address to key rate limits, lockouts, IP blocks, sessions and logs on.
154
+ * Every caller in the app must use this rather than reading request.ip or the headers itself.
155
+ */
156
+ export function getClientIp(request: FastifyRequest): string {
157
+ return resolveClientIp(request).ip;
158
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Cloudflare edge address ranges — the proof that a request really came through Cloudflare.
3
+ *
4
+ * `CF-Connecting-IP` names the real visitor, but it is just a header: anyone who reaches the
5
+ * server WITHOUT going through Cloudflare (the server's own IP, a sslip.io address, a grey-cloud
6
+ * domain) can send it with any value. So it is believed only when the machine that handed the
7
+ * request to our proxy is one of Cloudflare's own edge servers, i.e. its address is in these
8
+ * ranges (see client-ip.ts).
9
+ *
10
+ * The ranges are bundled so the check works offline and at the first request. Cloudflare
11
+ * changes them rarely; a background job (jobs/refresh-cloudflare-ranges.job.ts) refreshes them
12
+ * daily from the published lists. A refresh that fails, or returns something that does not look
13
+ * like the real list, keeps the current ranges: being out of date only means visitors behind a
14
+ * brand-new Cloudflare range are counted under that edge's address (strict, never spoofable).
15
+ *
16
+ * Source of the bundled list: https://www.cloudflare.com/ips-v4 and /ips-v6, fetched 2026-10-18.
17
+ */
18
+ import { BlockList, isIP } from 'node:net';
19
+ import { httpClient } from '@libs/http.js';
20
+ import { logger } from '@libs/logger.js';
21
+
22
+ export const CLOUDFLARE_IPV4_URL = 'https://www.cloudflare.com/ips-v4';
23
+ export const CLOUDFLARE_IPV6_URL = 'https://www.cloudflare.com/ips-v6';
24
+
25
+ export const BUNDLED_CLOUDFLARE_IPV4 = [
26
+ '173.245.48.0/20',
27
+ '103.21.244.0/22',
28
+ '103.22.200.0/22',
29
+ '103.31.4.0/22',
30
+ '141.101.64.0/18',
31
+ '108.162.192.0/18',
32
+ '190.93.240.0/20',
33
+ '188.114.96.0/20',
34
+ '197.234.240.0/22',
35
+ '198.41.128.0/17',
36
+ '162.158.0.0/15',
37
+ '104.16.0.0/13',
38
+ '104.24.0.0/14',
39
+ '172.64.0.0/13',
40
+ '131.0.72.0/22',
41
+ ] as const;
42
+
43
+ export const BUNDLED_CLOUDFLARE_IPV6 = [
44
+ '2400:cb00::/32',
45
+ '2606:4700::/32',
46
+ '2803:f800::/32',
47
+ '2405:b500::/32',
48
+ '2405:8100::/32',
49
+ '2a06:98c0::/29',
50
+ '2c0f:f248::/32',
51
+ ] as const;
52
+
53
+ // A downloaded list smaller than this is treated as broken (an error page, a truncated
54
+ // body) rather than as "Cloudflare shrank to two ranges overnight".
55
+ const MIN_IPV4_RANGES = 5;
56
+ const MIN_IPV6_RANGES = 1;
57
+
58
+ /** Parse one `address/prefix` line into a validated CIDR, or null when it is not one. */
59
+ function parseCidr(line: string, family: 4 | 6): { address: string; prefix: number } | null {
60
+ const [address, prefixText, extra] = line.trim().split('/');
61
+ if (!address || prefixText === undefined || extra !== undefined || isIP(address) !== family) return null;
62
+ if (!/^\d{1,3}$/.test(prefixText)) return null;
63
+ const prefix = Number(prefixText);
64
+ if (prefix < 0 || prefix > (family === 4 ? 32 : 128)) return null;
65
+ return { address, prefix };
66
+ }
67
+
68
+ /**
69
+ * Build a BlockList from both lists, or return null when either list is not a plausible copy
70
+ * of Cloudflare's (any unparseable line, or fewer ranges than the minimum).
71
+ */
72
+ export function buildRangeList(ipv4: readonly string[], ipv6: readonly string[]): BlockList | null {
73
+ const v4 = ipv4.map((l) => l.trim()).filter(Boolean);
74
+ const v6 = ipv6.map((l) => l.trim()).filter(Boolean);
75
+ if (v4.length < MIN_IPV4_RANGES || v6.length < MIN_IPV6_RANGES) return null;
76
+ const list = new BlockList();
77
+ for (const [lines, family] of [[v4, 4], [v6, 6]] as const) {
78
+ for (const line of lines) {
79
+ const cidr = parseCidr(line, family);
80
+ if (!cidr) return null;
81
+ list.addSubnet(cidr.address, cidr.prefix, family === 4 ? 'ipv4' : 'ipv6');
82
+ }
83
+ }
84
+ return list;
85
+ }
86
+
87
+ // Invariant: always a valid list; the bundled one cannot fail to build (unit-tested).
88
+ let current: BlockList = buildRangeList(BUNDLED_CLOUDFLARE_IPV4, BUNDLED_CLOUDFLARE_IPV6) as BlockList;
89
+
90
+ /** True when `ip` (an already-normalized IPv4 or IPv6 literal) belongs to Cloudflare's edge. */
91
+ export function isCloudflareIp(ip: string): boolean {
92
+ const family = isIP(ip);
93
+ if (family === 0) return false;
94
+ return current.check(ip, family === 4 ? 'ipv4' : 'ipv6');
95
+ }
96
+
97
+ /**
98
+ * Download the published lists and swap them in only when both look complete. Never throws:
99
+ * a refresh is an optimisation, and the bundled ranges stay valid if it fails.
100
+ *
101
+ * @returns true when the ranges were replaced
102
+ */
103
+ export async function refreshCloudflareRanges(): Promise<boolean> {
104
+ try {
105
+ const fetchList = async (url: string): Promise<string[]> => {
106
+ const res = await httpClient.get<string>(url, {
107
+ timeout: 10_000,
108
+ responseType: 'text',
109
+ headers: { Accept: 'text/plain' },
110
+ // Keep the raw text: axios would otherwise try to JSON-parse it.
111
+ transformResponse: [(data: unknown): unknown => data],
112
+ });
113
+ return typeof res.data === 'string' ? res.data.split(/\r?\n/) : [];
114
+ };
115
+ const [ipv4, ipv6] = await Promise.all([fetchList(CLOUDFLARE_IPV4_URL), fetchList(CLOUDFLARE_IPV6_URL)]);
116
+ const next = buildRangeList(ipv4, ipv6);
117
+ if (!next) {
118
+ logger.warn('[CLOUDFLARE] Downloaded IP ranges look incomplete; keeping the current list');
119
+ return false;
120
+ }
121
+ current = next;
122
+ return true;
123
+ } catch (error) {
124
+ logger.warn({ err: error }, '[CLOUDFLARE] Could not refresh IP ranges; keeping the current list');
125
+ return false;
126
+ }
127
+ }
128
+
129
+ /** Test hook: return to the bundled ranges. */
130
+ export function resetCloudflareRangesForTests(): void {
131
+ current = buildRangeList(BUNDLED_CLOUDFLARE_IPV4, BUNDLED_CLOUDFLARE_IPV6) as BlockList;
132
+ }
@@ -1,13 +1,51 @@
1
1
  import type { FastifyReply } from 'fastify';
2
2
  import { env } from '@config/env.js';
3
3
  import { parseDurationMs } from '@libs/duration.js';
4
+ import { logger } from '@libs/logger.js';
4
5
 
5
6
  const isProduction = env.NODE_ENV === 'production';
6
7
 
7
- // Cross-origin deployment: client and API on different subdomains require sameSite 'none'.
8
- // Same-origin deployment (or local dev): 'strict' is the safest default.
9
- const isCrossOrigin = Boolean(env.COOKIE_DOMAIN);
10
- const sameSitePolicy = isProduction && isCrossOrigin ? 'none' as const : 'strict' as const;
8
+ /**
9
+ * Production cookies are Secure, and browsers drop Secure cookies that arrive
10
+ * over plain http: a login "works" and the user is still signed out. env.ts
11
+ * warns at boot about an http CORS_ORIGIN; this catches the API itself being
12
+ * reached over http (request.protocol follows X-Forwarded-Proto from our own
13
+ * proxy, see trustProxy in app.ts). Logged once per process. localhost is
14
+ * exempt: browsers accept Secure cookies there.
15
+ */
16
+ let warnedPlainHttp = false;
17
+
18
+ function warnIfPlainHttp(reply: FastifyReply): void {
19
+ if (!isProduction || warnedPlainHttp) return;
20
+ const request = (reply as { request?: { protocol?: string; hostname?: string } }).request;
21
+ if (request?.protocol !== 'http') return;
22
+ if (['localhost', '127.0.0.1', '[::1]'].includes(request.hostname ?? '')) return;
23
+ warnedPlainHttp = true;
24
+ logger.warn(
25
+ '[COOKIES] Login cookies are Secure but this API was reached over plain http: browsers drop them, ' +
26
+ 'so users cannot stay signed in. Serve the API over https.',
27
+ );
28
+ }
29
+
30
+ /** Test hook: let the next plain-http login warn again. */
31
+ export function resetPlainHttpWarningForTests(): void {
32
+ warnedPlainHttp = false;
33
+ }
34
+
35
+ /**
36
+ * SameSite per cookie. Sibling subdomains (app.example.com + api.example.com)
37
+ * are the SAME site, and that is the only split deployment the template
38
+ * supports (auth_session must be shared through COOKIE_DOMAIN), so no cookie
39
+ * ever needs SameSite=None (sent along with requests from any website).
40
+ * - Token cookies: Strict. Only the client's own same-site fetches to the API
41
+ * need them, and Strict keeps every other website's requests bare.
42
+ * - auth_session: Lax. It is only a "signed in" marker read by the Next.js
43
+ * proxy (client src/proxy.ts, formerly middleware); Lax lets a link from
44
+ * another site (an email, a search result) carry it, so signed-in users
45
+ * are not bounced to /login on arrival.
46
+ */
47
+ const TOKEN_SAME_SITE = 'strict' as const;
48
+ const SESSION_SAME_SITE = 'lax' as const;
11
49
 
12
50
  /**
13
51
  * Cookie scope rules:
@@ -18,7 +56,7 @@ const sameSitePolicy = isProduction && isCrossOrigin ? 'none' as const : 'strict
18
56
  * only leak live logins to hosts that don't need them (a CNAME'd help desk,
19
57
  * another app on the same domain, a compromised subdomain).
20
58
  * - auth_session ("1", no secret) is the one cookie that must be visible to
21
- * the client host's Next.js middleware, so it alone uses COOKIE_DOMAIN
59
+ * the client host's Next.js proxy and JavaScript, so it alone uses COOKIE_DOMAIN
22
60
  * (e.g. ".example.com" covers app.example.com + api.example.com).
23
61
  */
24
62
  const sessionIndicatorDomain = env.COOKIE_DOMAIN || undefined;
@@ -38,7 +76,7 @@ const REFRESH_TOKEN_PATH = '/api/v1/auth';
38
76
  */
39
77
  function expireLegacyDomainTokenCookies(reply: FastifyReply): void {
40
78
  if (!sessionIndicatorDomain) return;
41
- const legacy = { httpOnly: true, secure: isProduction, sameSite: sameSitePolicy, domain: sessionIndicatorDomain };
79
+ const legacy = { httpOnly: true, secure: isProduction, sameSite: TOKEN_SAME_SITE, domain: sessionIndicatorDomain };
42
80
  reply.clearCookie('access_token', { ...legacy, path: ACCESS_TOKEN_PATH });
43
81
  reply.clearCookie('refresh_token', { ...legacy, path: REFRESH_TOKEN_PATH });
44
82
  }
@@ -48,12 +86,13 @@ export function setAuthCookies(
48
86
  accessToken: string,
49
87
  refreshToken: string,
50
88
  ): void {
89
+ warnIfPlainHttp(reply);
51
90
  expireLegacyDomainTokenCookies(reply);
52
91
 
53
92
  reply.setCookie('access_token', accessToken, {
54
93
  httpOnly: true,
55
94
  secure: isProduction,
56
- sameSite: sameSitePolicy,
95
+ sameSite: TOKEN_SAME_SITE,
57
96
  path: ACCESS_TOKEN_PATH,
58
97
  maxAge: Math.floor(ACCESS_TOKEN_MAX_AGE_MS / 1000), // setCookie expects seconds
59
98
  });
@@ -61,17 +100,17 @@ export function setAuthCookies(
61
100
  reply.setCookie('refresh_token', refreshToken, {
62
101
  httpOnly: true,
63
102
  secure: isProduction,
64
- sameSite: sameSitePolicy,
103
+ sameSite: TOKEN_SAME_SITE,
65
104
  path: REFRESH_TOKEN_PATH,
66
105
  maxAge: Math.floor(REFRESH_TOKEN_MAX_AGE_MS / 1000),
67
106
  });
68
107
 
69
- // Non-sensitive session indicator visible to Next.js middleware and client JS.
70
- // Lets middleware distinguish "never logged in" from "access token expired but session alive."
108
+ // Non-sensitive session indicator visible to the Next.js proxy and client JS.
109
+ // Lets the proxy distinguish "never logged in" from "access token expired but session alive."
71
110
  reply.setCookie('auth_session', '1', {
72
111
  httpOnly: false,
73
112
  secure: isProduction,
74
- sameSite: sameSitePolicy,
113
+ sameSite: SESSION_SAME_SITE,
75
114
  domain: sessionIndicatorDomain,
76
115
  path: '/',
77
116
  maxAge: Math.floor(REFRESH_TOKEN_MAX_AGE_MS / 1000),
@@ -84,21 +123,21 @@ export function clearAuthCookies(reply: FastifyReply): void {
84
123
  reply.clearCookie('access_token', {
85
124
  httpOnly: true,
86
125
  secure: isProduction,
87
- sameSite: sameSitePolicy,
126
+ sameSite: TOKEN_SAME_SITE,
88
127
  path: ACCESS_TOKEN_PATH,
89
128
  });
90
129
 
91
130
  reply.clearCookie('refresh_token', {
92
131
  httpOnly: true,
93
132
  secure: isProduction,
94
- sameSite: sameSitePolicy,
133
+ sameSite: TOKEN_SAME_SITE,
95
134
  path: REFRESH_TOKEN_PATH,
96
135
  });
97
136
 
98
137
  reply.clearCookie('auth_session', {
99
138
  httpOnly: false,
100
139
  secure: isProduction,
101
- sameSite: sameSitePolicy,
140
+ sameSite: SESSION_SAME_SITE,
102
141
  domain: sessionIndicatorDomain,
103
142
  path: '/',
104
143
  });
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Per-address email cap: at most EMAIL_PER_ADDRESS.max emails to one address per
3
+ * window (default 3 per hour).
4
+ *
5
+ * Why per address and not only per IP: the route limits are per IP, so someone
6
+ * with many IPs could otherwise flood one person's inbox and burn the sender's
7
+ * reputation and quota.
8
+ *
9
+ * Two separate counters per address, so a stranger cannot use up the owner's emails:
10
+ * - 'public': emails anyone can trigger by typing an address (forgot-password,
11
+ * the email-verification module's send-verification).
12
+ * - 'sign-in': the verification link re-sent when an unverified user signs in
13
+ * with the RIGHT password. Only someone who knows the password reaches it, so
14
+ * anonymous requests never drain it; it still has its own cap, because whoever
15
+ * registered an address (and so knows its password) could otherwise flood it.
16
+ * The single verification email sent at register is not capped at all: an
17
+ * address can register only once, so it cannot be used to flood anyone.
18
+ *
19
+ * Rules that keep it from leaking which accounts exist:
20
+ * - Call it BEFORE looking the user up, so unknown addresses are counted exactly
21
+ * like real ones and the 429 says nothing about the account.
22
+ * - The counter key is a SHA-256 of the address, so Redis never stores raw emails.
23
+ *
24
+ * Redis down → the email is allowed (fail open), like the other limiters.
25
+ */
26
+ import { createHash } from 'node:crypto';
27
+ import { EMAIL_PER_ADDRESS } from '@config/rate-limit.config.js';
28
+ import { getRedis } from '@libs/redis.js';
29
+ import { logger } from '@libs/logger.js';
30
+ import { TooManyRequestsError, describeWait } from '@shared/errors/errors.js';
31
+
32
+ /** Which counter an email is charged to (see the module header). */
33
+ export type EmailQuotaBucket = 'public' | 'sign-in';
34
+
35
+ const EMAIL_QUOTA_PREFIX: Record<EmailQuotaBucket, string> = {
36
+ public: 'email-quota:',
37
+ 'sign-in': 'email-quota:sign-in:',
38
+ };
39
+
40
+ export function emailQuotaKey(email: string, bucket: EmailQuotaBucket = 'public'): string {
41
+ return EMAIL_QUOTA_PREFIX[bucket] + createHash('sha256').update(email.trim().toLowerCase()).digest('hex');
42
+ }
43
+
44
+ /**
45
+ * Count one email to `email` in `bucket`. Throws 429 EMAIL_RATE_LIMITED (with
46
+ * retryAfterSeconds) once that counter is over its quota for the window.
47
+ */
48
+ export async function consumeEmailQuota(email: string, bucket: EmailQuotaBucket = 'public'): Promise<void> {
49
+ const key = emailQuotaKey(email, bucket);
50
+ let ttlMs: number;
51
+ try {
52
+ const redis = getRedis();
53
+ const count = await redis.incr(key);
54
+ if (count === 1) {
55
+ await redis.pexpire(key, EMAIL_PER_ADDRESS.timeWindow);
56
+ }
57
+ if (count <= EMAIL_PER_ADDRESS.max) return;
58
+ ttlMs = await redis.pttl(key);
59
+ if (ttlMs < 0) {
60
+ // The expiry was lost (e.g. the PEXPIRE failed): restart the window rather than block forever.
61
+ await redis.pexpire(key, EMAIL_PER_ADDRESS.timeWindow);
62
+ ttlMs = EMAIL_PER_ADDRESS.timeWindow;
63
+ }
64
+ } catch {
65
+ logger.warn('[EMAIL-QUOTA] Redis unavailable, sending without the per-address cap');
66
+ return;
67
+ }
68
+ const seconds = Math.max(1, Math.ceil(ttlMs / 1000));
69
+ throw new TooManyRequestsError(
70
+ `Too many emails were sent to this address. Try again in ${describeWait(seconds)}.`,
71
+ 'EMAIL_RATE_LIMITED',
72
+ seconds,
73
+ );
74
+ }