create-tigra 3.2.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +160 -44
  4. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  5. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  6. package/modules/email-verification/server/verification.controller.ts +3 -1
  7. package/modules/email-verification/server/verification.service.ts +81 -21
  8. package/package.json +3 -2
  9. package/template/.github/dependabot.yml +47 -0
  10. package/template/.github/workflows/audit.yml +36 -0
  11. package/template/.github/workflows/ci.yml +79 -0
  12. package/template/AGENTS.md +18 -9
  13. package/template/client/.dockerignore +1 -0
  14. package/template/client/.env.example.production +13 -2
  15. package/template/client/AGENTS.md +13 -5
  16. package/template/client/Dockerfile +186 -14
  17. package/template/client/next.config.ts +1 -1
  18. package/template/client/package-lock.json +15983 -14181
  19. package/template/client/package.json +56 -48
  20. package/template/client/scripts/check-sharp.mjs +53 -0
  21. package/template/client/scripts/next-dev.cjs +5 -1
  22. package/template/client/src/__tests__/proxy.test.ts +92 -0
  23. package/template/client/src/app/healthz/route.ts +16 -0
  24. package/template/client/src/app/layout.tsx +9 -3
  25. package/template/client/src/app/page.tsx +2 -2
  26. package/template/client/src/app/providers.tsx +23 -4
  27. package/template/client/src/components/layout/Header.tsx +7 -3
  28. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  29. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  30. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  31. package/template/client/src/features/auth/components/AuthInitializer.tsx +38 -19
  32. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  33. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  34. package/template/client/src/features/auth/components/LoginForm.tsx +18 -4
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
  37. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  38. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  39. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  40. package/template/client/src/features/auth/types/auth.types.ts +3 -0
  41. package/template/client/src/instrumentation-client.ts +9 -1
  42. package/template/client/src/instrumentation.ts +6 -0
  43. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  44. package/template/client/src/lib/api/api.types.ts +14 -0
  45. package/template/client/src/lib/api/axios.config.ts +101 -15
  46. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  47. package/template/client/src/lib/api/session-events.ts +29 -0
  48. package/template/client/src/lib/constants/routes.ts +12 -0
  49. package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
  50. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  51. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  52. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  53. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  54. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  55. package/template/client/src/lib/utils/error.ts +86 -1
  56. package/template/client/src/lib/utils/form.ts +31 -0
  57. package/template/client/src/lib/utils/paths.ts +18 -0
  58. package/template/client/src/lib/utils/security.ts +37 -0
  59. package/template/client/src/lib/utils/session-marker.ts +24 -0
  60. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  61. package/template/client/src/store/__tests__/store.test.ts +44 -0
  62. package/template/client/src/store/index.ts +26 -8
  63. package/template/client/vitest.config.mts +48 -0
  64. package/template/server/.env.example +280 -269
  65. package/template/server/.env.example.production +283 -236
  66. package/template/server/AGENTS.md +13 -4
  67. package/template/server/Dockerfile +181 -14
  68. package/template/server/docker-compose.yml +4 -2
  69. package/template/server/docs/deployment.md +63 -0
  70. package/template/server/docs/logging.md +52 -4
  71. package/template/server/docs/rate-limits.md +153 -0
  72. package/template/server/docs/testing.md +63 -0
  73. package/template/server/eslint.config.mjs +19 -0
  74. package/template/server/package-lock.json +8784 -8743
  75. package/template/server/package.json +79 -75
  76. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  77. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  78. package/template/server/prisma/schema.prisma +19 -6
  79. package/template/server/prisma/seed.ts +13 -5
  80. package/template/server/scripts/check-heic.mjs +40 -0
  81. package/template/server/scripts/check-sharp.mjs +53 -0
  82. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  83. package/template/server/src/app.ts +248 -335
  84. package/template/server/src/config/__tests__/env.test.ts +219 -0
  85. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  86. package/template/server/src/config/env.ts +326 -171
  87. package/template/server/src/config/rate-limit.config.ts +157 -106
  88. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
  89. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  90. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  91. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  92. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +81 -65
  93. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  94. package/template/server/src/jobs/index.ts +12 -2
  95. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  96. package/template/server/src/jobs/schedule.ts +50 -0
  97. package/template/server/src/libs/__tests__/auth.test.ts +168 -0
  98. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  99. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  100. package/template/server/src/libs/__tests__/cookies.test.ts +113 -0
  101. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  102. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  103. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  104. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  105. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  106. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  107. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  108. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  109. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  110. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  111. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  112. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  113. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  114. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  115. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  116. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  117. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  118. package/template/server/src/libs/__tests__/redis.test.ts +59 -0
  119. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  120. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  121. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  122. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -0
  123. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  124. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  125. package/template/server/src/libs/account-status.ts +52 -0
  126. package/template/server/src/libs/auth.ts +51 -12
  127. package/template/server/src/libs/client-ip.ts +158 -77
  128. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  129. package/template/server/src/libs/cookies.ts +91 -24
  130. package/template/server/src/libs/email-quota.ts +74 -0
  131. package/template/server/src/libs/email.ts +46 -9
  132. package/template/server/src/libs/error-handler.ts +111 -0
  133. package/template/server/src/libs/health-routes.ts +53 -0
  134. package/template/server/src/libs/http.ts +139 -47
  135. package/template/server/src/libs/ip-address.ts +37 -0
  136. package/template/server/src/libs/ip-block.ts +284 -220
  137. package/template/server/src/libs/logger.ts +41 -12
  138. package/template/server/src/libs/monitoring.ts +131 -42
  139. package/template/server/src/libs/observability/sentry.ts +80 -0
  140. package/template/server/src/libs/origin-check.ts +9 -7
  141. package/template/server/src/libs/prisma.ts +47 -4
  142. package/template/server/src/libs/query-counter.ts +71 -59
  143. package/template/server/src/libs/rate-limiting.ts +110 -0
  144. package/template/server/src/libs/redis-required.ts +28 -0
  145. package/template/server/src/libs/redis.ts +108 -18
  146. package/template/server/src/libs/request-id.ts +18 -0
  147. package/template/server/src/libs/requestLogger.ts +112 -17
  148. package/template/server/src/libs/safe-http.ts +101 -0
  149. package/template/server/src/libs/shutdown.ts +87 -0
  150. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  151. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +143 -0
  152. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  153. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  154. package/template/server/src/libs/storage/file-storage.service.ts +104 -83
  155. package/template/server/src/libs/storage/file-validator.ts +48 -46
  156. package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
  157. package/template/server/src/libs/token-hash.ts +18 -0
  158. package/template/server/src/libs/url-safety.ts +127 -121
  159. package/template/server/src/libs/validation-errors.ts +86 -0
  160. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  161. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  162. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  163. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  164. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  165. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  166. package/template/server/src/modules/admin/admin.repo.ts +56 -13
  167. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  168. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  169. package/template/server/src/modules/admin/admin.service.ts +73 -7
  170. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  171. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  172. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  173. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +332 -49
  174. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  175. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  176. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  177. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  178. package/template/server/src/modules/auth/auth.repo.ts +60 -42
  179. package/template/server/src/modules/auth/auth.schemas.ts +5 -2
  180. package/template/server/src/modules/auth/auth.service.ts +197 -109
  181. package/template/server/src/modules/auth/session.repo.ts +12 -12
  182. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  183. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  184. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  185. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  186. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  187. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  188. package/template/server/src/modules/users/users.controller.ts +9 -38
  189. package/template/server/src/modules/users/users.repo.ts +25 -7
  190. package/template/server/src/modules/users/users.routes.ts +3 -22
  191. package/template/server/src/modules/users/users.schemas.ts +15 -9
  192. package/template/server/src/modules/users/users.service.ts +105 -93
  193. package/template/server/src/scripts/make-admin.ts +48 -0
  194. package/template/server/src/server.ts +48 -26
  195. package/template/server/src/shared/errors/AppError.ts +27 -1
  196. package/template/server/src/shared/errors/errors.ts +42 -5
  197. package/template/server/src/shared/responses/successResponse.ts +22 -3
  198. package/template/server/src/shared/types/index.ts +7 -0
  199. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  200. package/template/server/src/test/integration-helpers.ts +343 -0
  201. package/template/server/src/test/integration-services.ts +74 -0
  202. package/template/server/src/test/integration.global-setup.ts +144 -0
  203. package/template/server/src/test/integration.setup.ts +35 -158
  204. package/template/server/src/test/setup.ts +23 -8
  205. package/template/server/tsconfig.build.json +1 -1
  206. package/template/server/tsconfig.json +1 -0
  207. package/template/server/vitest.config.ts +17 -4
  208. package/template/server/vitest.integration.config.ts +18 -13
  209. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -1,121 +1,257 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import type { FastifyRequest } from 'fastify';
3
-
4
- // Mock the env module so each test can flip TRUST_CLOUDFLARE without relying on
5
- // process.env load order (src/config/env.ts validates + exits on import).
6
- const mockEnv = vi.hoisted(() => ({ TRUST_CLOUDFLARE: false }));
7
- vi.mock('@config/env.js', () => ({ env: mockEnv }));
8
-
9
- import { getClientIp } from '../client-ip.js';
10
-
11
- // Minimal FastifyRequest stub — getClientIp only reads `.ip` and `.headers`.
12
- function makeRequest(ip: string, headers: Record<string, unknown> = {}): FastifyRequest {
13
- return { ip, headers } as unknown as FastifyRequest;
14
- }
15
-
16
- describe('getClientIp', () => {
17
- beforeEach(() => {
18
- mockEnv.TRUST_CLOUDFLARE = false;
19
- });
20
-
21
- describe('when TRUST_CLOUDFLARE is false (default)', () => {
22
- it('returns request.ip and ignores the CF-Connecting-IP header', () => {
23
- const request = makeRequest('10.0.0.1', { 'cf-connecting-ip': '203.0.113.7' });
24
- expect(getClientIp(request)).toBe('10.0.0.1');
25
- });
26
-
27
- it('returns request.ip when no CF header is present', () => {
28
- expect(getClientIp(makeRequest('10.0.0.1'))).toBe('10.0.0.1');
29
- });
30
- });
31
-
32
- describe('when TRUST_CLOUDFLARE is true', () => {
33
- beforeEach(() => {
34
- mockEnv.TRUST_CLOUDFLARE = true;
35
- });
36
-
37
- it('returns the CF-Connecting-IP header value', () => {
38
- const request = makeRequest('10.0.0.1', { 'cf-connecting-ip': '203.0.113.7' });
39
- expect(getClientIp(request)).toBe('203.0.113.7');
40
- });
41
-
42
- it('falls back to request.ip when the CF header is absent', () => {
43
- expect(getClientIp(makeRequest('10.0.0.1'))).toBe('10.0.0.1');
44
- });
45
-
46
- it('falls back to request.ip when the CF header is an empty string', () => {
47
- const request = makeRequest('10.0.0.1', { 'cf-connecting-ip': '' });
48
- expect(getClientIp(request)).toBe('10.0.0.1');
49
- });
50
-
51
- it('falls back to request.ip when the CF header is an array (duplicated header)', () => {
52
- const request = makeRequest('10.0.0.1', { 'cf-connecting-ip': ['203.0.113.7', '198.51.100.2'] });
53
- expect(getClientIp(request)).toBe('10.0.0.1');
54
- });
55
-
56
- it('falls through an array CF header to a valid X-Forwarded-For entry', () => {
57
- // CF header is an array (untrusted shape) so it falls through; XFF is then used.
58
- const request = makeRequest('10.0.0.1', {
59
- 'cf-connecting-ip': ['203.0.113.7', '198.51.100.2'],
60
- 'x-forwarded-for': '198.51.100.9',
61
- });
62
- expect(getClientIp(request)).toBe('198.51.100.9');
63
- });
64
-
65
- it('prefers a valid CF header over X-Forwarded-For', () => {
66
- const request = makeRequest('10.0.0.1', {
67
- 'cf-connecting-ip': '203.0.113.7',
68
- 'x-forwarded-for': '198.51.100.9',
69
- });
70
- expect(getClientIp(request)).toBe('203.0.113.7');
71
- });
72
-
73
- it('falls through to X-Forwarded-For when the CF header is an invalid IP', () => {
74
- const request = makeRequest('10.0.0.1', {
75
- 'cf-connecting-ip': 'not-an-ip',
76
- 'x-forwarded-for': '198.51.100.9',
77
- });
78
- expect(getClientIp(request)).toBe('198.51.100.9');
79
- });
80
- });
81
-
82
- describe('X-Forwarded-For resolution (independent of the flag)', () => {
83
- it('uses the left-most XFF entry when the CF flag is on but the CF header is absent', () => {
84
- mockEnv.TRUST_CLOUDFLARE = true;
85
- const request = makeRequest('10.0.0.1', { 'x-forwarded-for': '203.0.113.7' });
86
- expect(getClientIp(request)).toBe('203.0.113.7');
87
- });
88
-
89
- it('uses the left-most XFF entry even when the CF flag is off (grey-cloud / DNS-only)', () => {
90
- const request = makeRequest('10.0.0.1', { 'x-forwarded-for': '203.0.113.7' });
91
- expect(getClientIp(request)).toBe('203.0.113.7');
92
- });
93
-
94
- it('returns the left-most entry of a multi-hop XFF chain', () => {
95
- const request = makeRequest('10.0.0.1', {
96
- 'x-forwarded-for': '203.0.113.7, 70.41.3.18, 150.172.238.178',
97
- });
98
- expect(getClientIp(request)).toBe('203.0.113.7');
99
- });
100
-
101
- it('trims surrounding whitespace from the XFF entry', () => {
102
- const request = makeRequest('10.0.0.1', { 'x-forwarded-for': ' 203.0.113.7 , 70.41.3.18' });
103
- expect(getClientIp(request)).toBe('203.0.113.7');
104
- });
105
-
106
- it('falls back to request.ip when the XFF entry is not a valid IP', () => {
107
- const request = makeRequest('10.0.0.1', { 'x-forwarded-for': 'garbage, 70.41.3.18' });
108
- expect(getClientIp(request)).toBe('10.0.0.1');
109
- });
110
-
111
- it('falls back to request.ip when the XFF header is an empty string', () => {
112
- const request = makeRequest('10.0.0.1', { 'x-forwarded-for': '' });
113
- expect(getClientIp(request)).toBe('10.0.0.1');
114
- });
115
-
116
- it('uses the first element when XFF is an array (duplicated header)', () => {
117
- const request = makeRequest('10.0.0.1', { 'x-forwarded-for': ['203.0.113.7', '70.41.3.18'] });
118
- expect(getClientIp(request)).toBe('203.0.113.7');
119
- });
120
- });
121
- });
1
+ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
2
+ import Fastify, { type FastifyInstance } from 'fastify';
3
+ import { env } from '@config/env.js';
4
+ import { logger } from '@libs/logger.js';
5
+ import {
6
+ normalizeIp,
7
+ resolveClientIp,
8
+ getClientIp,
9
+ TRUSTED_PROXY_RANGES,
10
+ UNVERIFIED_CLOUDFLARE_KEY,
11
+ UNVERIFIED_WARNING_INTERVAL_MS,
12
+ resetUnverifiedWarningForTests,
13
+ } from '../client-ip.js';
14
+
15
+ // Real Fastify with the app's own trustProxy setting, so proxy-addr walks X-Forwarded-For exactly
16
+ // as in production. `remoteAddress` is the TCP peer: a public address = a direct visitor,
17
+ // 10.0.1.5 = Coolify's Traefik on the Docker network, 173.245.48.10 = a Cloudflare edge server.
18
+ const TRAEFIK = '10.0.1.5';
19
+ const CF_EDGE = '173.245.48.10';
20
+ const CF_EDGE_V6 = '2400:cb00::1';
21
+ const VISITOR = '203.0.113.7';
22
+ const OTHER_VISITOR = '198.51.100.20';
23
+ const FORGED = '6.6.6.6';
24
+
25
+ let app: FastifyInstance;
26
+
27
+ beforeAll(async () => {
28
+ app = Fastify({ trustProxy: TRUSTED_PROXY_RANGES });
29
+ app.get('/ip', async (request) => ({ ...resolveClientIp(request), key: getClientIp(request) }));
30
+ await app.ready();
31
+ });
32
+
33
+ afterAll(async () => {
34
+ await app.close();
35
+ });
36
+
37
+ async function resolve(remoteAddress: string, headers: Record<string, string | string[]> = {}): Promise<{ ip: string; source: string; key: string }> {
38
+ const res = await app.inject({ method: 'GET', url: '/ip', remoteAddress, headers });
39
+ return res.json();
40
+ }
41
+
42
+ describe('resolveClientIp — a visitor that reaches the app directly (no trusted proxy)', () => {
43
+ it('uses the TCP peer', async () => {
44
+ expect(await resolve(VISITOR)).toEqual({ ip: VISITOR, source: 'socket', key: VISITOR });
45
+ });
46
+
47
+ it('ignores X-Forwarded-For and CF-Connecting-IP written by that visitor', async () => {
48
+ const r = await resolve(VISITOR, { 'x-forwarded-for': FORGED, 'cf-connecting-ip': OTHER_VISITOR });
49
+ expect(r).toMatchObject({ ip: VISITOR, source: 'socket' });
50
+ });
51
+ });
52
+
53
+ describe('resolveClientIp — behind our own proxy (Traefik), no Cloudflare', () => {
54
+ it('uses the address the proxy recorded', async () => {
55
+ expect(await resolve(TRAEFIK, { 'x-forwarded-for': VISITOR })).toMatchObject({ ip: VISITOR, source: 'proxy' });
56
+ });
57
+
58
+ it('ignores entries the visitor wrote to the left of it (the old spoofing hole)', async () => {
59
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': `${FORGED}, 10.0.0.9, ${VISITOR}` });
60
+ expect(r).toMatchObject({ ip: VISITOR, source: 'proxy' });
61
+ });
62
+
63
+ it('ignores a forged CF-Connecting-IP when the hop is not Cloudflare (sslip.io, grey cloud, server IP)', async () => {
64
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': VISITOR, 'cf-connecting-ip': FORGED });
65
+ expect(r).toMatchObject({ ip: VISITOR, source: 'proxy' });
66
+ });
67
+
68
+ it('skips further trusted internal hops to the right', async () => {
69
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': `${VISITOR}, 10.0.0.9` });
70
+ expect(r).toMatchObject({ ip: VISITOR, source: 'proxy' });
71
+ });
72
+
73
+ it('gives two visitors two different keys (no shared counter through one proxy)', async () => {
74
+ const a = await resolve(TRAEFIK, { 'x-forwarded-for': VISITOR });
75
+ const b = await resolve(TRAEFIK, { 'x-forwarded-for': OTHER_VISITOR });
76
+ expect(a.key).not.toBe(b.key);
77
+ });
78
+
79
+ it('falls back to the proxy address when the proxy sent no X-Forwarded-For', async () => {
80
+ expect(await resolve(TRAEFIK)).toMatchObject({ ip: TRAEFIK, source: 'socket' });
81
+ expect(await resolve(TRAEFIK, { 'x-forwarded-for': '' })).toMatchObject({ ip: TRAEFIK });
82
+ });
83
+ });
84
+
85
+ describe('resolveClientIp — through Cloudflare', () => {
86
+ it('Cloudflare then our proxy: uses CF-Connecting-IP, never the edge address', async () => {
87
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': `${FORGED}, ${OTHER_VISITOR}, ${CF_EDGE}`, 'cf-connecting-ip': OTHER_VISITOR });
88
+ expect(r).toEqual({ ip: OTHER_VISITOR, source: 'cloudflare', key: OTHER_VISITOR });
89
+ });
90
+
91
+ it('two visitors behind the same Cloudflare edge get two keys (the old shared lockout)', async () => {
92
+ const a = await resolve(TRAEFIK, { 'x-forwarded-for': `${VISITOR}, ${CF_EDGE}`, 'cf-connecting-ip': VISITOR });
93
+ const b = await resolve(TRAEFIK, { 'x-forwarded-for': `${OTHER_VISITOR}, ${CF_EDGE}`, 'cf-connecting-ip': OTHER_VISITOR });
94
+ expect([a.key, b.key]).toEqual([VISITOR, OTHER_VISITOR]);
95
+ });
96
+
97
+ it('Cloudflare connecting to the app directly also works', async () => {
98
+ expect(await resolve(CF_EDGE, { 'cf-connecting-ip': VISITOR })).toMatchObject({ ip: VISITOR, source: 'cloudflare' });
99
+ });
100
+
101
+ it('works for an IPv6 edge and an IPv6 visitor', async () => {
102
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': `2001:db8::5, ${CF_EDGE_V6}`, 'cf-connecting-ip': '2001:DB8::5' });
103
+ expect(r).toMatchObject({ ip: '2001:db8::5', source: 'cloudflare' });
104
+ });
105
+
106
+ it('a Cloudflare hop with a missing or invalid header stays on the edge address (strict, not spoofable)', async () => {
107
+ const variants: Record<string, string | string[]>[] = [{}, { 'cf-connecting-ip': '' }, { 'cf-connecting-ip': 'not-an-ip' }, { 'cf-connecting-ip': [VISITOR, FORGED] }];
108
+ for (const headers of variants) {
109
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, ...headers });
110
+ expect(r.ip).toBe(CF_EDGE);
111
+ }
112
+ });
113
+ });
114
+
115
+ describe('resolveClientIp — Cloudflare requests that are not genuine traffic of this zone', () => {
116
+ // A Cloudflare Worker (anyone's) fetching the app through a non-Cloudflare hostname leaves from
117
+ // Cloudflare's ranges and may set CF-Connecting-IP freely; Cloudflare stamps such requests with
118
+ // CF-Worker. They must land in one fixed bucket, whatever address they claim.
119
+ it('without a secret: a CF-Worker-stamped request is unverified and keyed on one fixed bucket', async () => {
120
+ const a = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': FORGED, 'cf-worker': 'attacker.example' });
121
+ const b = await resolve(TRAEFIK, { 'x-forwarded-for': '104.16.0.9', 'cf-connecting-ip': OTHER_VISITOR, 'cf-worker': 'x' });
122
+ expect(a).toEqual({ ip: UNVERIFIED_CLOUDFLARE_KEY, source: 'cloudflare-unverified', key: UNVERIFIED_CLOUDFLARE_KEY });
123
+ expect(b.key).toBe(a.key);
124
+ });
125
+
126
+ describe('with CLOUDFLARE_ORIGIN_SECRET set', () => {
127
+ const SECRET = 'a'.repeat(40);
128
+ beforeAll(() => {
129
+ env.CLOUDFLARE_ORIGIN_SECRET = SECRET;
130
+ });
131
+ afterAll(() => {
132
+ env.CLOUDFLARE_ORIGIN_SECRET = undefined;
133
+ });
134
+
135
+ it('believes CF-Connecting-IP only with the matching origin secret', async () => {
136
+ const ok = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': VISITOR, 'x-origin-verify': SECRET });
137
+ expect(ok).toMatchObject({ ip: VISITOR, source: 'cloudflare' });
138
+ });
139
+
140
+ it('a missing, wrong, wrong-length or repeated secret is unverified (fixed bucket)', async () => {
141
+ const variants: Record<string, string | string[]>[] = [
142
+ {},
143
+ { 'x-origin-verify': 'b'.repeat(40) },
144
+ { 'x-origin-verify': 'short' },
145
+ { 'x-origin-verify': [SECRET, SECRET] },
146
+ ];
147
+ for (const extra of variants) {
148
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': FORGED, ...extra });
149
+ expect(r).toMatchObject({ ip: UNVERIFIED_CLOUDFLARE_KEY, source: 'cloudflare-unverified' });
150
+ }
151
+ });
152
+
153
+ it('the owner\'s own zone traffic is believed even when stamped by one of the owner\'s Workers', async () => {
154
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': VISITOR, 'x-origin-verify': SECRET, 'cf-worker': 'owner.example' });
155
+ expect(r).toMatchObject({ ip: VISITOR, source: 'cloudflare' });
156
+ });
157
+
158
+ it('a non-Cloudflare hop never uses CF-Connecting-IP, secret or not', async () => {
159
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': VISITOR, 'cf-connecting-ip': FORGED, 'x-origin-verify': SECRET });
160
+ expect(r).toMatchObject({ ip: VISITOR, source: 'proxy' });
161
+ });
162
+ });
163
+ });
164
+
165
+ describe('resolveClientIp — address forms and broken input', () => {
166
+ it('normalizes IPv4-mapped IPv6 and upper-case IPv6 so one visitor has one key', async () => {
167
+ expect(await resolve(`::ffff:${VISITOR}`)).toMatchObject({ ip: VISITOR, source: 'socket' });
168
+ expect(await resolve(TRAEFIK, { 'x-forwarded-for': '2001:DB8::1' })).toMatchObject({ ip: '2001:db8::1' });
169
+ });
170
+
171
+ it('treats an IPv4-mapped proxy address as our proxy', async () => {
172
+ expect(await resolve(`::ffff:${TRAEFIK}`, { 'x-forwarded-for': VISITOR })).toMatchObject({ ip: VISITOR, source: 'proxy' });
173
+ });
174
+
175
+ it('several X-Forwarded-For headers are read as one list, right-most first', async () => {
176
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': [FORGED, VISITOR] });
177
+ expect(r.ip).toBe(VISITOR);
178
+ });
179
+
180
+ it('always returns a non-empty key, whatever the headers contain', async () => {
181
+ for (const xff of ['garbage', ',,,', ' , 999.1.1.1', `${VISITOR}, garbage`]) {
182
+ const r = await resolve(TRAEFIK, { 'x-forwarded-for': xff });
183
+ expect(r.key.length).toBeGreaterThan(0);
184
+ }
185
+ });
186
+ });
187
+
188
+ describe('normalizeIp', () => {
189
+ it('accepts IPv4/IPv6 literals and rejects everything else', () => {
190
+ expect(normalizeIp(' 203.0.113.7 ')).toBe('203.0.113.7');
191
+ expect(normalizeIp('::FFFF:203.0.113.7')).toBe('203.0.113.7');
192
+ expect(normalizeIp('2001:DB8::1')).toBe('2001:db8::1');
193
+ expect(normalizeIp('::ffff:not-ip')).toBeUndefined();
194
+ expect(normalizeIp('')).toBeUndefined();
195
+ expect(normalizeIp(undefined)).toBeUndefined();
196
+ expect(normalizeIp('example.com')).toBeUndefined();
197
+ });
198
+
199
+ it('gives every spelling of one address the same canonical form', () => {
200
+ expect(normalizeIp('2001:0DB8:0000::0001')).toBe('2001:db8::1');
201
+ expect(normalizeIp('2001:db8:0:0:0:0:0:1')).toBe('2001:db8::1');
202
+ expect(normalizeIp('::ffff:cb00:7107')).toBe('203.0.113.7'); // hex IPv4-mapped
203
+ expect(normalizeIp('::1')).toBe('::1');
204
+ expect(normalizeIp('FE80::1%ETH0')).toBe('fe80::1%eth0'); // zone id: lower-cased only
205
+ });
206
+ });
207
+
208
+ describe('TRUST_CLOUDFLARE is gone', () => {
209
+ it('a leftover TRUST_CLOUDFLARE value is ignored by the env schema', async () => {
210
+ vi.resetModules();
211
+ process.env.TRUST_CLOUDFLARE = 'true';
212
+ try {
213
+ const { env } = await import('@config/env.js');
214
+ expect('TRUST_CLOUDFLARE' in env).toBe(false);
215
+ } finally {
216
+ delete process.env.TRUST_CLOUDFLARE;
217
+ }
218
+ });
219
+ });
220
+
221
+ describe('warning when Cloudflare traffic lands in the shared bucket', () => {
222
+ // On a correctly set up zone this never happens, so the operator must hear about it:
223
+ // every such visitor shares ONE rate-limit counter.
224
+ const unverified = { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': FORGED, 'cf-worker': 'someone.example' };
225
+
226
+ afterAll(() => {
227
+ vi.useRealTimers();
228
+ vi.restoreAllMocks();
229
+ });
230
+
231
+ it('logs one warning per interval, not one per request, and never the header values', async () => {
232
+ resetUnverifiedWarningForTests();
233
+ vi.useFakeTimers({ toFake: ['Date'] });
234
+ vi.setSystemTime(new Date('2026-10-19T10:00:00Z'));
235
+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined as never);
236
+
237
+ for (let i = 0; i < 5; i++) await resolve(TRAEFIK, unverified);
238
+ expect(warn).toHaveBeenCalledTimes(1);
239
+ const message = String(warn.mock.calls[0]?.[0]);
240
+ expect(message).toContain('share one rate-limit bucket');
241
+ expect(message).not.toContain(FORGED);
242
+ expect(message).not.toContain('someone.example');
243
+
244
+ vi.setSystemTime(new Date(Date.now() + UNVERIFIED_WARNING_INTERVAL_MS + 1));
245
+ await resolve(TRAEFIK, unverified);
246
+ expect(warn).toHaveBeenCalledTimes(2);
247
+ });
248
+
249
+ it('does not warn for verified Cloudflare traffic or for direct visitors', async () => {
250
+ resetUnverifiedWarningForTests();
251
+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined as never);
252
+ warn.mockClear();
253
+ await resolve(TRAEFIK, { 'x-forwarded-for': CF_EDGE, 'cf-connecting-ip': VISITOR });
254
+ await resolve(VISITOR);
255
+ expect(warn).not.toHaveBeenCalled();
256
+ });
257
+ });
@@ -0,0 +1,79 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ const { get } = vi.hoisted(() => ({ get: vi.fn() }));
4
+ vi.mock('@libs/http.js', () => ({ httpClient: { get } }));
5
+ vi.mock('@libs/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
6
+
7
+ import {
8
+ BUNDLED_CLOUDFLARE_IPV4,
9
+ BUNDLED_CLOUDFLARE_IPV6,
10
+ CLOUDFLARE_IPV4_URL,
11
+ buildRangeList,
12
+ isCloudflareIp,
13
+ refreshCloudflareRanges,
14
+ resetCloudflareRangesForTests,
15
+ } from '../cloudflare-ranges.js';
16
+
17
+ /** Make the mocked HTTP client answer the two list URLs with these bodies. */
18
+ function serve(ipv4: string, ipv6: string): void {
19
+ get.mockImplementation(async (url: string) => ({ data: url === CLOUDFLARE_IPV4_URL ? ipv4 : ipv6 }));
20
+ }
21
+
22
+ const NEW_V4 = ['192.0.2.0/24', '198.18.0.0/15', '100.64.0.0/10', '233.252.0.0/24', '240.0.0.0/8'].join('\n');
23
+ const NEW_V6 = '2001:db8:cf::/48';
24
+
25
+ beforeEach(() => {
26
+ get.mockReset();
27
+ resetCloudflareRangesForTests();
28
+ });
29
+
30
+ describe('bundled ranges', () => {
31
+ it('build without error and recognise Cloudflare edges, IPv4 and IPv6', () => {
32
+ expect(buildRangeList(BUNDLED_CLOUDFLARE_IPV4, BUNDLED_CLOUDFLARE_IPV6)).not.toBeNull();
33
+ expect(isCloudflareIp('173.245.48.10')).toBe(true);
34
+ expect(isCloudflareIp('104.16.1.1')).toBe(true);
35
+ expect(isCloudflareIp('2606:4700::1')).toBe(true);
36
+ });
37
+
38
+ it('do not contain ordinary, private or malformed addresses', () => {
39
+ for (const ip of ['8.8.8.8', '203.0.113.7', '10.0.1.5', '172.20.0.1', '::1', '2001:db8::1', 'garbage', '']) {
40
+ expect(isCloudflareIp(ip)).toBe(false);
41
+ }
42
+ });
43
+ });
44
+
45
+ describe('refreshCloudflareRanges', () => {
46
+ it('swaps in a complete downloaded list', async () => {
47
+ serve(NEW_V4, NEW_V6);
48
+ expect(await refreshCloudflareRanges()).toBe(true);
49
+ expect(isCloudflareIp('192.0.2.10')).toBe(true);
50
+ expect(isCloudflareIp('2001:db8:cf::1')).toBe(true);
51
+ expect(isCloudflareIp('173.245.48.10')).toBe(false);
52
+ });
53
+
54
+ it('keeps the current list when the download fails', async () => {
55
+ get.mockRejectedValue(new Error('network down'));
56
+ expect(await refreshCloudflareRanges()).toBe(false);
57
+ expect(isCloudflareIp('173.245.48.10')).toBe(true);
58
+ });
59
+
60
+ it('keeps the current list for an error page, a truncated list or a bad line', async () => {
61
+ for (const [v4, v6] of [
62
+ ['<html>rate limited</html>', NEW_V6],
63
+ ['192.0.2.0/24\n198.18.0.0/15', NEW_V6],
64
+ [`${NEW_V4}\n300.1.1.0/24`, NEW_V6],
65
+ [NEW_V4, ''],
66
+ [NEW_V4, '2001:db8::/200'],
67
+ ]) {
68
+ serve(v4, v6);
69
+ expect(await refreshCloudflareRanges()).toBe(false);
70
+ expect(isCloudflareIp('173.245.48.10')).toBe(true);
71
+ }
72
+ });
73
+
74
+ it('tolerates Windows line endings and blank lines', async () => {
75
+ serve(`${NEW_V4.replace(/\n/g, '\r\n')}\r\n\r\n`, `${NEW_V6}\n`);
76
+ expect(await refreshCloudflareRanges()).toBe(true);
77
+ expect(isCloudflareIp('100.64.0.1')).toBe(true);
78
+ });
79
+ });
@@ -0,0 +1,113 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import type { FastifyReply } from 'fastify';
3
+ import { setAuthCookies, clearAuthCookies, resetPlainHttpWarningForTests } from '../cookies.js';
4
+ import { logger } from '@libs/logger.js';
5
+
6
+ // Production cross-subdomain setup: only the non-secret auth_session indicator
7
+ // may use COOKIE_DOMAIN; the bearer token cookies must stay host-only.
8
+
9
+ vi.mock('@config/env.js', () => ({
10
+ env: {
11
+ NODE_ENV: 'production',
12
+ COOKIE_DOMAIN: '.example.test',
13
+ JWT_ACCESS_EXPIRY: '15m',
14
+ JWT_REFRESH_EXPIRY: '7d',
15
+ },
16
+ }));
17
+
18
+ vi.mock('@libs/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
19
+
20
+ type CookieOpts = { domain?: string; path?: string; httpOnly?: boolean; secure?: boolean; sameSite?: string };
21
+
22
+ function fakeReply(): { reply: FastifyReply; set: Map<string, CookieOpts>; cleared: Array<[string, CookieOpts]> } {
23
+ const set = new Map<string, CookieOpts>();
24
+ const cleared: Array<[string, CookieOpts]> = [];
25
+ const reply = {
26
+ setCookie: vi.fn((name: string, _value: string, opts: CookieOpts) => set.set(name, opts)),
27
+ clearCookie: vi.fn((name: string, opts: CookieOpts) => cleared.push([name, opts])),
28
+ } as unknown as FastifyReply;
29
+ return { reply, set, cleared };
30
+ }
31
+
32
+ describe('setAuthCookies', () => {
33
+ it('keeps access and refresh tokens host-only and shares only auth_session', () => {
34
+ const { reply, set } = fakeReply();
35
+ setAuthCookies(reply, 'access', 'refresh');
36
+
37
+ expect(set.get('access_token')?.domain).toBeUndefined();
38
+ expect(set.get('refresh_token')?.domain).toBeUndefined();
39
+ expect(set.get('access_token')?.httpOnly).toBe(true);
40
+ expect(set.get('access_token')?.secure).toBe(true);
41
+ expect(set.get('auth_session')?.domain).toBe('.example.test');
42
+ });
43
+
44
+ it('expires legacy domain-wide token cookies from older versions', () => {
45
+ const { reply, cleared } = fakeReply();
46
+ setAuthCookies(reply, 'access', 'refresh');
47
+
48
+ expect(cleared).toContainEqual(['access_token', expect.objectContaining({ domain: '.example.test', path: '/' })]);
49
+ expect(cleared).toContainEqual([
50
+ 'refresh_token',
51
+ expect.objectContaining({ domain: '.example.test', path: '/api/v1/auth' }),
52
+ ]);
53
+ });
54
+ });
55
+
56
+ describe('SameSite (never None, even with COOKIE_DOMAIN in production)', () => {
57
+ it('sets the token cookies Strict and the auth_session marker Lax', () => {
58
+ const { reply, set } = fakeReply();
59
+ setAuthCookies(reply, 'access', 'refresh');
60
+
61
+ expect(set.get('access_token')?.sameSite).toBe('strict');
62
+ expect(set.get('refresh_token')?.sameSite).toBe('strict');
63
+ expect(set.get('auth_session')?.sameSite).toBe('lax');
64
+ });
65
+
66
+ it('clears with the same policies, and nothing anywhere is None', () => {
67
+ const { reply, set, cleared } = fakeReply();
68
+ setAuthCookies(reply, 'access', 'refresh');
69
+ clearAuthCookies(reply);
70
+
71
+ for (const [name, opts] of cleared) {
72
+ expect(opts.sameSite, name).toBe(name === 'auth_session' ? 'lax' : 'strict');
73
+ }
74
+ expect([...set.values(), ...cleared.map(([, o]) => o)].some((o) => o.sameSite === 'none')).toBe(false);
75
+ });
76
+ });
77
+
78
+ describe('clearAuthCookies', () => {
79
+ it('clears both the host-only tokens and any legacy domain-wide copies', () => {
80
+ const { reply, cleared } = fakeReply();
81
+ clearAuthCookies(reply);
82
+
83
+ const tokenClears = cleared.filter(([name]) => name === 'access_token');
84
+ expect(tokenClears.map(([, o]) => o.domain).sort()).toEqual(['.example.test', undefined].sort());
85
+ expect(cleared).toContainEqual(['auth_session', expect.objectContaining({ domain: '.example.test' })]);
86
+ });
87
+ });
88
+
89
+ describe('plain-http warning (production cookies are Secure)', () => {
90
+ function replyOver(protocol: string, hostname = 'api.example.test'): FastifyReply {
91
+ const { reply } = fakeReply();
92
+ (reply as unknown as { request: unknown }).request = { protocol, hostname };
93
+ return reply;
94
+ }
95
+
96
+ it('warns once when the API is reached over http', () => {
97
+ resetPlainHttpWarningForTests();
98
+ vi.mocked(logger.warn).mockClear();
99
+ setAuthCookies(replyOver('http'), 'a', 'r');
100
+ setAuthCookies(replyOver('http'), 'a', 'r');
101
+ expect(logger.warn).toHaveBeenCalledTimes(1);
102
+ expect(vi.mocked(logger.warn).mock.calls[0]?.[0]).toContain('plain http');
103
+ });
104
+
105
+ it('stays quiet over https, on localhost, and when the request is unknown', () => {
106
+ resetPlainHttpWarningForTests();
107
+ vi.mocked(logger.warn).mockClear();
108
+ setAuthCookies(replyOver('https'), 'a', 'r');
109
+ setAuthCookies(replyOver('http', 'localhost'), 'a', 'r');
110
+ setAuthCookies(fakeReply().reply, 'a', 'r');
111
+ expect(logger.warn).not.toHaveBeenCalled();
112
+ });
113
+ });