create-tigra 3.3.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 (203) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +72 -10
  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 +44 -13
  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 +35 -18
  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 +13 -2
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  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/lib/api/__tests__/axios.config.test.ts +183 -0
  41. package/template/client/src/lib/api/api.types.ts +14 -0
  42. package/template/client/src/lib/api/axios.config.ts +101 -15
  43. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  44. package/template/client/src/lib/api/session-events.ts +29 -0
  45. package/template/client/src/lib/constants/routes.ts +12 -0
  46. package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
  47. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  48. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  49. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  50. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  51. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  52. package/template/client/src/lib/utils/error.ts +81 -0
  53. package/template/client/src/lib/utils/form.ts +31 -0
  54. package/template/client/src/lib/utils/paths.ts +18 -0
  55. package/template/client/src/lib/utils/session-marker.ts +24 -0
  56. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  57. package/template/client/src/store/__tests__/store.test.ts +44 -0
  58. package/template/client/src/store/index.ts +26 -8
  59. package/template/client/vitest.config.mts +48 -0
  60. package/template/server/.env.example +280 -270
  61. package/template/server/.env.example.production +283 -242
  62. package/template/server/AGENTS.md +13 -4
  63. package/template/server/Dockerfile +176 -14
  64. package/template/server/docker-compose.yml +4 -2
  65. package/template/server/docs/deployment.md +63 -0
  66. package/template/server/docs/logging.md +52 -4
  67. package/template/server/docs/rate-limits.md +153 -0
  68. package/template/server/docs/testing.md +63 -0
  69. package/template/server/eslint.config.mjs +19 -0
  70. package/template/server/package-lock.json +8784 -8743
  71. package/template/server/package.json +79 -75
  72. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  73. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  74. package/template/server/prisma/schema.prisma +0 -3
  75. package/template/server/scripts/check-heic.mjs +40 -0
  76. package/template/server/scripts/check-sharp.mjs +53 -0
  77. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  78. package/template/server/src/app.ts +248 -346
  79. package/template/server/src/config/__tests__/env.test.ts +219 -0
  80. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  81. package/template/server/src/config/env.ts +326 -182
  82. package/template/server/src/config/rate-limit.config.ts +157 -106
  83. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  84. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  85. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  86. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  87. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  88. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  89. package/template/server/src/jobs/index.ts +12 -2
  90. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  91. package/template/server/src/jobs/schedule.ts +50 -0
  92. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  93. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  94. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  95. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  96. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  97. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  98. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  99. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  100. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  101. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  102. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  103. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  104. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  105. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  106. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  107. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  108. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  109. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  110. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  111. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  112. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  113. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  114. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  115. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  116. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  117. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  118. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  119. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  120. package/template/server/src/libs/auth.ts +39 -10
  121. package/template/server/src/libs/client-ip.ts +158 -77
  122. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  123. package/template/server/src/libs/cookies.ts +53 -14
  124. package/template/server/src/libs/email-quota.ts +74 -0
  125. package/template/server/src/libs/email.ts +46 -9
  126. package/template/server/src/libs/error-handler.ts +111 -0
  127. package/template/server/src/libs/health-routes.ts +53 -0
  128. package/template/server/src/libs/http.ts +139 -47
  129. package/template/server/src/libs/ip-address.ts +37 -0
  130. package/template/server/src/libs/ip-block.ts +284 -221
  131. package/template/server/src/libs/logger.ts +41 -12
  132. package/template/server/src/libs/monitoring.ts +127 -41
  133. package/template/server/src/libs/observability/sentry.ts +1 -1
  134. package/template/server/src/libs/origin-check.ts +9 -7
  135. package/template/server/src/libs/prisma.ts +47 -4
  136. package/template/server/src/libs/query-counter.ts +71 -59
  137. package/template/server/src/libs/rate-limiting.ts +110 -0
  138. package/template/server/src/libs/redis-required.ts +28 -0
  139. package/template/server/src/libs/redis.ts +27 -1
  140. package/template/server/src/libs/request-id.ts +18 -0
  141. package/template/server/src/libs/requestLogger.ts +112 -17
  142. package/template/server/src/libs/safe-http.ts +101 -0
  143. package/template/server/src/libs/shutdown.ts +87 -0
  144. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  145. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  146. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  147. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  148. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  149. package/template/server/src/libs/storage/file-validator.ts +48 -46
  150. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  151. package/template/server/src/libs/token-hash.ts +18 -0
  152. package/template/server/src/libs/url-safety.ts +127 -121
  153. package/template/server/src/libs/validation-errors.ts +86 -0
  154. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  155. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  156. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  157. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  158. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  159. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  160. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  161. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  162. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  163. package/template/server/src/modules/admin/admin.service.ts +66 -4
  164. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  165. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  166. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  167. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  168. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  170. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  171. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  172. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  173. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  174. package/template/server/src/modules/auth/auth.service.ts +167 -96
  175. package/template/server/src/modules/auth/session.repo.ts +12 -0
  176. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  177. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  178. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  179. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  180. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  181. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  182. package/template/server/src/modules/users/users.controller.ts +9 -38
  183. package/template/server/src/modules/users/users.repo.ts +23 -7
  184. package/template/server/src/modules/users/users.routes.ts +3 -22
  185. package/template/server/src/modules/users/users.schemas.ts +15 -9
  186. package/template/server/src/modules/users/users.service.ts +105 -93
  187. package/template/server/src/scripts/make-admin.ts +48 -0
  188. package/template/server/src/server.ts +48 -26
  189. package/template/server/src/shared/errors/AppError.ts +27 -1
  190. package/template/server/src/shared/errors/errors.ts +42 -5
  191. package/template/server/src/shared/responses/successResponse.ts +22 -3
  192. package/template/server/src/shared/types/index.ts +7 -0
  193. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  194. package/template/server/src/test/integration-helpers.ts +343 -0
  195. package/template/server/src/test/integration-services.ts +74 -0
  196. package/template/server/src/test/integration.global-setup.ts +144 -0
  197. package/template/server/src/test/integration.setup.ts +35 -158
  198. package/template/server/src/test/setup.ts +3 -10
  199. package/template/server/tsconfig.build.json +1 -1
  200. package/template/server/tsconfig.json +1 -0
  201. package/template/server/vitest.config.ts +17 -4
  202. package/template/server/vitest.integration.config.ts +18 -13
  203. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -1,221 +1,284 @@
1
- /**
2
- * IP Blocking Service
3
- *
4
- * Two-tier IP blocking:
5
- * - Permanent blocks: DB (source of truth) + Redis SET (hot cache). Admin-managed via API.
6
- * - Auto-blocks: Redis ZSET with expiry timestamps (triggered by excessive rate-limit violations)
7
- *
8
- * Design decisions:
9
- * - DB is the source of truth for permanent blocks — survives Redis restarts
10
- * - Redis is the hot cache — all runtime checks hit Redis only (O(1))
11
- * - On server boot, syncBlockedIpsToRedis() loads all permanent blocks from DB into Redis
12
- * - Fails open: if Redis is down, requests are NOT blocked (availability > security for rate limiting)
13
- * - Lazy cleanup: expired auto-blocks are removed on check, no separate cleanup job needed
14
- */
15
-
16
- import { env } from '@config/env.js';
17
- import { prisma } from '@libs/prisma.js';
18
- import { getRedis } from '@libs/redis.js';
19
- import { logger } from '@libs/logger.js';
20
- import { ConflictError } from '@shared/errors/errors.js';
21
- import { isPrivateOrReservedIp } from '@libs/url-safety.js';
22
-
23
- // Redis keys
24
- const BLOCKED_IPS_KEY = 'blocked_ips';
25
- const AUTO_BLOCKED_KEY = 'auto_blocked_ips';
26
- const VIOLATION_PREFIX = 'rl_violations:';
27
-
28
- // Auto-block thresholds — env-configurable (see .env.example).
29
- // The threshold default is deliberately high (20): auto-block must catch
30
- // SUSTAINED abuse, not a single burst. Rate-limit counting happens before
31
- // validation, so a retry-looping but legitimate client (or a NAT'd office
32
- // sharing one egress IP) can rack up violations quickly — see the self-ban
33
- // interaction note in src/config/rate-limit.config.ts before lowering it.
34
- const AUTO_BLOCK_THRESHOLD = env.IP_AUTO_BLOCK_THRESHOLD; // violations before auto-block (default 20)
35
- const AUTO_BLOCK_WINDOW_SECONDS = env.IP_AUTO_BLOCK_WINDOW_SECONDS; // sliding window (default 300 = 5 min)
36
- const AUTO_BLOCK_DURATION_SECONDS = env.IP_AUTO_BLOCK_DURATION_SECONDS; // block duration (default 3600 = 1 hour)
37
-
38
- /**
39
- * Sync all permanent blocked IPs from DB to Redis.
40
- * Called once during server startup.
41
- */
42
- export async function syncBlockedIpsToRedis(): Promise<void> {
43
- try {
44
- const blockedIps = await prisma.blockedIp.findMany({ select: { ip: true } });
45
-
46
- const redis = getRedis();
47
-
48
- // Clear stale Redis state and repopulate from DB
49
- await redis.del(BLOCKED_IPS_KEY);
50
-
51
- if (blockedIps.length > 0) {
52
- await redis.sadd(BLOCKED_IPS_KEY, ...blockedIps.map((b) => b.ip));
53
- }
54
-
55
- logger.info(`[IP-BLOCK] Synced ${blockedIps.length} blocked IPs from DB to Redis`);
56
- } catch (error) {
57
- logger.warn('[IP-BLOCK] Failed to sync blocked IPs from DB to Redis — permanent blocks may not be enforced until next restart');
58
- logger.debug(error);
59
- }
60
- }
61
-
62
- /**
63
- * Check if an IP is blocked (permanent or auto-blocked).
64
- *
65
- * @param ip - IP address to check
66
- * @returns true if blocked, false otherwise (including Redis failures)
67
- */
68
- export async function isIpBlocked(ip: string): Promise<boolean> {
69
- try {
70
- const redis = getRedis();
71
-
72
- // Check permanent block list
73
- const permanent = await redis.sismember(BLOCKED_IPS_KEY, ip);
74
- if (permanent === 1) return true;
75
-
76
- // Check auto-block list (score = expiry Unix timestamp)
77
- const score = await redis.zscore(AUTO_BLOCKED_KEY, ip);
78
- if (score) {
79
- const expiresAt = Number(score);
80
- if (expiresAt > Date.now() / 1000) return true;
81
-
82
- // Expired — clean up lazily
83
- await redis.zrem(AUTO_BLOCKED_KEY, ip);
84
- }
85
-
86
- return false;
87
- } catch {
88
- // Fail open: if Redis is down, don't block
89
- logger.warn('[IP-BLOCK] Redis unavailable, skipping IP block check');
90
- return false;
91
- }
92
- }
93
-
94
- /**
95
- * Block an IP permanently. Writes to DB (source of truth) + Redis (hot cache).
96
- *
97
- * @param ip - IP address to block
98
- * @param blockedBy - Admin user ID who initiated the block
99
- * @param reason - Optional reason for the block
100
- */
101
- export async function blockIp(
102
- ip: string,
103
- blockedBy: string,
104
- reason?: string,
105
- ): Promise<{ id: string; ip: string; reason: string | null; blockedBy: string | null; createdAt: Date }> {
106
- // Write to DB (source of truth)
107
- const existing = await prisma.blockedIp.findUnique({ where: { ip } });
108
- if (existing) {
109
- throw new ConflictError('IP is already blocked', 'IP_ALREADY_BLOCKED');
110
- }
111
-
112
- const blocked = await prisma.blockedIp.create({
113
- data: { ip, blockedBy, reason: reason ?? null },
114
- });
115
-
116
- // Sync to Redis cache
117
- try {
118
- const redis = getRedis();
119
- await redis.sadd(BLOCKED_IPS_KEY, ip);
120
- } catch {
121
- logger.warn({ ip }, '[IP-BLOCK] Failed to sync block to Redis — will be synced on next restart');
122
- }
123
-
124
- logger.info({ ip, blockedBy, reason }, '[IP-BLOCK] IP permanently blocked');
125
- return blocked;
126
- }
127
-
128
- /**
129
- * Unblock an IP. Removes from DB + Redis + auto-block list.
130
- *
131
- * @param ip - IP address to unblock
132
- */
133
- export async function unblockIp(ip: string): Promise<void> {
134
- // Remove from DB
135
- await prisma.blockedIp.deleteMany({ where: { ip } });
136
-
137
- // Remove from Redis (both permanent and auto-block)
138
- try {
139
- const redis = getRedis();
140
- await redis.srem(BLOCKED_IPS_KEY, ip);
141
- await redis.zrem(AUTO_BLOCKED_KEY, ip);
142
- } catch {
143
- logger.warn({ ip }, '[IP-BLOCK] Failed to sync unblock to Redis — will be synced on next restart');
144
- }
145
-
146
- logger.info({ ip }, '[IP-BLOCK] IP unblocked');
147
- }
148
-
149
- /**
150
- * List all currently blocked IPs (permanent from DB + active auto-blocks from Redis).
151
- */
152
- export async function getBlockedIps(): Promise<{
153
- // blockedBy is null once the admin who created the block has been purged.
154
- permanent: { id: string; ip: string; reason: string | null; blockedBy: string | null; createdAt: Date }[];
155
- autoBlocked: string[];
156
- }> {
157
- // Permanent blocks from DB (source of truth)
158
- const permanent = await prisma.blockedIp.findMany({
159
- select: { id: true, ip: true, reason: true, blockedBy: true, createdAt: true },
160
- orderBy: { createdAt: 'desc' },
161
- });
162
-
163
- // Auto-blocks from Redis
164
- let autoBlocked: string[] = [];
165
- try {
166
- const redis = getRedis();
167
- const nowSeconds = Date.now() / 1000;
168
- autoBlocked = await redis.zrangebyscore(AUTO_BLOCKED_KEY, nowSeconds, '+inf');
169
- } catch {
170
- logger.warn('[IP-BLOCK] Redis unavailable, cannot retrieve auto-blocked IPs');
171
- }
172
-
173
- return { permanent, autoBlocked };
174
- }
175
-
176
- /**
177
- * Record a rate-limit violation for an IP.
178
- *
179
- * If the IP exceeds AUTO_BLOCK_THRESHOLD violations within
180
- * AUTO_BLOCK_WINDOW_SECONDS, it gets auto-blocked for
181
- * AUTO_BLOCK_DURATION_SECONDS.
182
- *
183
- * Called from the rate-limit `onExceeded` callback.
184
- *
185
- * @param ip - IP address that violated rate limit
186
- */
187
- export async function recordRateLimitViolation(ip: string): Promise<void> {
188
- // Never auto-block infrastructure addresses (loopback / private / link-local /
189
- // Traefik-Docker internal). A shared proxy IP getting auto-blocked would lock
190
- // out every real user behind it. Public client IPs proceed as normal.
191
- if (isPrivateOrReservedIp(ip)) {
192
- return;
193
- }
194
-
195
- try {
196
- const redis = getRedis();
197
- const key = `${VIOLATION_PREFIX}${ip}`;
198
-
199
- const count = await redis.incr(key);
200
-
201
- // Set TTL on first violation (sliding window)
202
- if (count === 1) {
203
- await redis.expire(key, AUTO_BLOCK_WINDOW_SECONDS);
204
- }
205
-
206
- if (count >= AUTO_BLOCK_THRESHOLD) {
207
- // Auto-block: add to ZSET with expiry timestamp as score
208
- const expiresAt = Math.floor(Date.now() / 1000) + AUTO_BLOCK_DURATION_SECONDS;
209
- await redis.zadd(AUTO_BLOCKED_KEY, expiresAt, ip);
210
- await redis.del(key); // Reset violation counter
211
-
212
- logger.warn(
213
- { ip, violations: count, blockedForSeconds: AUTO_BLOCK_DURATION_SECONDS },
214
- '[IP-BLOCK] Auto-blocked IP due to excessive rate-limit violations',
215
- );
216
- }
217
- } catch {
218
- // Non-critical: don't break the request if violation tracking fails
219
- logger.warn('[IP-BLOCK] Failed to record rate-limit violation');
220
- }
221
- }
1
+ /**
2
+ * IP Blocking Service
3
+ *
4
+ * Two-tier IP blocking:
5
+ * - Permanent blocks: DB (source of truth) + Redis SET (hot cache). Admin-managed via API.
6
+ * - Auto-blocks: Redis ZSET with expiry timestamps (triggered by excessive rate-limit violations)
7
+ *
8
+ * Design decisions:
9
+ * - DB is the source of truth for permanent blocks — survives Redis restarts
10
+ * - Redis is the hot cache — all runtime checks hit Redis only (O(1))
11
+ * - On server boot, syncBlockedIpsToRedis() loads all permanent blocks from DB into Redis
12
+ * - Fails open: if Redis is down, requests are NOT blocked (availability > security for rate limiting)
13
+ * - Lazy cleanup: expired auto-blocks are removed on check, no separate cleanup job needed
14
+ * - One spelling: every stored or removed block is the canonical form
15
+ * (normalizeIp, libs/ip-address.ts), the same string the visitor's requests
16
+ * are checked with. A block typed as `2001:DB8::1` used to never match.
17
+ * - No self-lockout: a block applies to every route, the unblock route
18
+ * included, so an admin may not block the address they are using, nor a
19
+ * private/reserved address (a proxy or Docker address would block everyone).
20
+ */
21
+
22
+ import { env } from '@config/env.js';
23
+ import { prisma, isPrismaUniqueViolation } from '@libs/prisma.js';
24
+ import { getRedis } from '@libs/redis.js';
25
+ import { logger } from '@libs/logger.js';
26
+ import { ConflictError, ValidationError } from '@shared/errors/errors.js';
27
+ import { isPrivateOrReservedIp } from '@libs/url-safety.js';
28
+ import { normalizeIp } from '@libs/ip-address.js';
29
+
30
+ // Redis keys
31
+ const BLOCKED_IPS_KEY = 'blocked_ips';
32
+ const AUTO_BLOCKED_KEY = 'auto_blocked_ips';
33
+ const VIOLATION_PREFIX = 'rl_violations:';
34
+
35
+ // Auto-block thresholds — env-configurable (see .env.example).
36
+ // The threshold default is deliberately high (20): auto-block must catch
37
+ // SUSTAINED abuse, not a single burst. Rate-limit counting happens before
38
+ // validation, so a retry-looping but legitimate client (or a NAT'd office
39
+ // sharing one egress IP) can rack up violations quickly — see the self-ban
40
+ // interaction note in src/config/rate-limit.config.ts before lowering it.
41
+ const AUTO_BLOCK_THRESHOLD = env.IP_AUTO_BLOCK_THRESHOLD; // violations before auto-block (default 20)
42
+ const AUTO_BLOCK_WINDOW_SECONDS = env.IP_AUTO_BLOCK_WINDOW_SECONDS; // sliding window (default 300 = 5 min)
43
+ const AUTO_BLOCK_DURATION_SECONDS = env.IP_AUTO_BLOCK_DURATION_SECONDS; // block duration (default 3600 = 1 hour)
44
+
45
+ /**
46
+ * Sync all permanent blocked IPs from DB to Redis.
47
+ * Called once during server startup.
48
+ */
49
+ export async function syncBlockedIpsToRedis(): Promise<void> {
50
+ try {
51
+ const blockedIps = await prisma.blockedIp.findMany({ select: { ip: true } });
52
+
53
+ const redis = getRedis();
54
+
55
+ // Clear stale Redis state and repopulate from DB
56
+ await redis.del(BLOCKED_IPS_KEY);
57
+
58
+ if (blockedIps.length > 0) {
59
+ await redis.sadd(BLOCKED_IPS_KEY, ...blockedIps.map((b) => b.ip));
60
+ }
61
+
62
+ logger.info(`[IP-BLOCK] Synced ${blockedIps.length} blocked IPs from DB to Redis`);
63
+ } catch (error) {
64
+ logger.warn('[IP-BLOCK] Failed to sync blocked IPs from DB to Redis — permanent blocks may not be enforced until next restart');
65
+ logger.debug(error);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Block state of one IP.
71
+ * - `permanent`: an admin block, no end time.
72
+ * - `retryAfterSeconds`: set for an automatic block, the whole seconds until it
73
+ * ends, so the 403 can tell the visitor when to come back.
74
+ */
75
+ export type IpBlock =
76
+ | { blocked: false }
77
+ | { blocked: true; permanent: true }
78
+ | { blocked: true; permanent: false; retryAfterSeconds: number };
79
+
80
+ /**
81
+ * Check if an IP is blocked (permanent or auto-blocked).
82
+ *
83
+ * @param ip - IP address to check
84
+ * @returns the block state; `{ blocked: false }` also on Redis failures (fail open)
85
+ */
86
+ export async function getIpBlock(ip: string): Promise<IpBlock> {
87
+ try {
88
+ const redis = getRedis();
89
+
90
+ // Check permanent block list
91
+ const permanent = await redis.sismember(BLOCKED_IPS_KEY, ip);
92
+ if (permanent === 1) return { blocked: true, permanent: true };
93
+
94
+ // Check auto-block list (score = expiry Unix timestamp)
95
+ const score = await redis.zscore(AUTO_BLOCKED_KEY, ip);
96
+ if (score) {
97
+ const secondsLeft = Number(score) - Date.now() / 1000;
98
+ if (secondsLeft > 0) {
99
+ return { blocked: true, permanent: false, retryAfterSeconds: Math.max(1, Math.ceil(secondsLeft)) };
100
+ }
101
+
102
+ // Expired — clean up lazily
103
+ await redis.zrem(AUTO_BLOCKED_KEY, ip);
104
+ }
105
+
106
+ return { blocked: false };
107
+ } catch {
108
+ // Fail open: if Redis is down, don't block
109
+ logger.warn('[IP-BLOCK] Redis unavailable, skipping IP block check');
110
+ return { blocked: false };
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Block an IP permanently. Writes to DB (source of truth) + Redis (hot cache).
116
+ *
117
+ * @param rawIp - IP address to block, in any spelling (stored canonical)
118
+ * @param blockedBy - Admin user ID who initiated the block
119
+ * @param reason - Optional reason for the block
120
+ * @param requesterIp - The admin's own resolved address (getClientIp), never blockable
121
+ * @throws ValidationError 422 CANNOT_BLOCK_OWN_IP / IP_NOT_BLOCKABLE / INVALID_IP
122
+ * @throws ConflictError 409 IP_ALREADY_BLOCKED (also for a parallel duplicate)
123
+ */
124
+ export async function blockIp(
125
+ rawIp: string,
126
+ blockedBy: string,
127
+ reason: string | undefined,
128
+ requesterIp: string,
129
+ ): Promise<{ id: string; ip: string; reason: string | null; blockedBy: string | null; createdAt: Date }> {
130
+ const ip = normalizeIp(rawIp);
131
+ if (!ip) {
132
+ throw new ValidationError('Invalid IP address', 'INVALID_IP');
133
+ }
134
+ if (ip === normalizeIp(requesterIp)) {
135
+ throw new ValidationError('You cannot block the address you are using', 'CANNOT_BLOCK_OWN_IP');
136
+ }
137
+ if (isPrivateOrReservedIp(ip)) {
138
+ throw new ValidationError('Private and reserved addresses cannot be blocked', 'IP_NOT_BLOCKABLE');
139
+ }
140
+
141
+ // Write to DB (source of truth)
142
+ const existing = await prisma.blockedIp.findUnique({ where: { ip } });
143
+ if (existing) {
144
+ throw new ConflictError('IP is already blocked', 'IP_ALREADY_BLOCKED');
145
+ }
146
+
147
+ let blocked;
148
+ try {
149
+ blocked = await prisma.blockedIp.create({
150
+ data: { ip, blockedBy, reason: reason ?? null },
151
+ });
152
+ } catch (error) {
153
+ // A parallel request blocked the same address between our check and insert.
154
+ if (isPrismaUniqueViolation(error)) {
155
+ throw new ConflictError('IP is already blocked', 'IP_ALREADY_BLOCKED');
156
+ }
157
+ throw error;
158
+ }
159
+
160
+ // Sync to Redis cache
161
+ try {
162
+ const redis = getRedis();
163
+ await redis.sadd(BLOCKED_IPS_KEY, ip);
164
+ } catch {
165
+ logger.warn({ ip }, '[IP-BLOCK] Failed to sync block to Redis — will be synced on next restart');
166
+ }
167
+
168
+ logger.info({ ip, blockedBy, reason }, '[IP-BLOCK] IP permanently blocked');
169
+ return blocked;
170
+ }
171
+
172
+ /**
173
+ * Unblock an IP. Removes from DB + Redis + auto-block list.
174
+ *
175
+ * @param rawIp - IP address to unblock, in any spelling (matched canonical)
176
+ */
177
+ export async function unblockIp(rawIp: string): Promise<void> {
178
+ const ip = normalizeIp(rawIp) ?? rawIp.trim();
179
+ // Remove from DB
180
+ await prisma.blockedIp.deleteMany({ where: { ip } });
181
+
182
+ // Remove from Redis (both permanent and auto-block)
183
+ try {
184
+ const redis = getRedis();
185
+ await redis.srem(BLOCKED_IPS_KEY, ip);
186
+ await redis.zrem(AUTO_BLOCKED_KEY, ip);
187
+ } catch {
188
+ logger.warn({ ip }, '[IP-BLOCK] Failed to sync unblock to Redis — will be synced on next restart');
189
+ }
190
+
191
+ logger.info({ ip }, '[IP-BLOCK] IP unblocked');
192
+ }
193
+
194
+ /**
195
+ * Remove every automatic block whose end time has passed. getIpBlock removes
196
+ * an expired entry only when that same IP comes back, so IPs that never return
197
+ * would stay in the list forever. Called by the hourly cleanup job
198
+ * (jobs/cleanup-expired-auth.job.ts). Fail-open: with Redis down it does
199
+ * nothing and reports 0.
200
+ *
201
+ * @returns how many expired entries were removed
202
+ */
203
+ export async function pruneExpiredAutoBlocks(nowSeconds: number = Date.now() / 1000): Promise<number> {
204
+ try {
205
+ return await getRedis().zremrangebyscore(AUTO_BLOCKED_KEY, '-inf', nowSeconds);
206
+ } catch {
207
+ logger.warn('[IP-BLOCK] Redis unavailable, expired automatic blocks not pruned this time');
208
+ return 0;
209
+ }
210
+ }
211
+
212
+ /**
213
+ * List all currently blocked IPs (permanent from DB + active auto-blocks from Redis).
214
+ */
215
+ export async function getBlockedIps(): Promise<{
216
+ // blockedBy is null once the admin who created the block has been purged.
217
+ permanent: { id: string; ip: string; reason: string | null; blockedBy: string | null; createdAt: Date }[];
218
+ autoBlocked: string[];
219
+ }> {
220
+ // Permanent blocks from DB (source of truth)
221
+ const permanent = await prisma.blockedIp.findMany({
222
+ select: { id: true, ip: true, reason: true, blockedBy: true, createdAt: true },
223
+ orderBy: { createdAt: 'desc' },
224
+ });
225
+
226
+ // Auto-blocks from Redis
227
+ let autoBlocked: string[] = [];
228
+ try {
229
+ const redis = getRedis();
230
+ const nowSeconds = Date.now() / 1000;
231
+ autoBlocked = await redis.zrangebyscore(AUTO_BLOCKED_KEY, nowSeconds, '+inf');
232
+ } catch {
233
+ logger.warn('[IP-BLOCK] Redis unavailable, cannot retrieve auto-blocked IPs');
234
+ }
235
+
236
+ return { permanent, autoBlocked };
237
+ }
238
+
239
+ /**
240
+ * Record a rate-limit violation for an IP.
241
+ *
242
+ * If the IP exceeds AUTO_BLOCK_THRESHOLD violations within
243
+ * AUTO_BLOCK_WINDOW_SECONDS, it gets auto-blocked for
244
+ * AUTO_BLOCK_DURATION_SECONDS.
245
+ *
246
+ * Called from the rate-limit `onExceeded` callback.
247
+ *
248
+ * @param ip - IP address that violated rate limit
249
+ */
250
+ export async function recordRateLimitViolation(ip: string): Promise<void> {
251
+ // Never auto-block infrastructure addresses (loopback / private / link-local /
252
+ // Traefik-Docker internal). A shared proxy IP getting auto-blocked would lock
253
+ // out every real user behind it. Public client IPs proceed as normal.
254
+ if (isPrivateOrReservedIp(ip)) {
255
+ return;
256
+ }
257
+
258
+ try {
259
+ const redis = getRedis();
260
+ const key = `${VIOLATION_PREFIX}${ip}`;
261
+
262
+ const count = await redis.incr(key);
263
+
264
+ // Set TTL on first violation (sliding window)
265
+ if (count === 1) {
266
+ await redis.expire(key, AUTO_BLOCK_WINDOW_SECONDS);
267
+ }
268
+
269
+ if (count >= AUTO_BLOCK_THRESHOLD) {
270
+ // Auto-block: add to ZSET with expiry timestamp as score
271
+ const expiresAt = Math.floor(Date.now() / 1000) + AUTO_BLOCK_DURATION_SECONDS;
272
+ await redis.zadd(AUTO_BLOCKED_KEY, expiresAt, ip);
273
+ await redis.del(key); // Reset violation counter
274
+
275
+ logger.warn(
276
+ { ip, violations: count, blockedForSeconds: AUTO_BLOCK_DURATION_SECONDS },
277
+ '[IP-BLOCK] Auto-blocked IP due to excessive rate-limit violations',
278
+ );
279
+ }
280
+ } catch {
281
+ // Non-critical: don't break the request if violation tracking fails
282
+ logger.warn('[IP-BLOCK] Failed to record rate-limit violation');
283
+ }
284
+ }
@@ -1,21 +1,50 @@
1
1
  import pino from 'pino';
2
2
  import { env } from '@config/env.js';
3
3
 
4
+ /**
5
+ * Field names that never reach the logs, wherever they sit in a logged object
6
+ * from the top level down to three levels deep (and inside arrays there).
7
+ * A safety net: no template code logs these today, but a debug line such as
8
+ * `logger.info(request.body)` must not leak a password. To protect a new
9
+ * field, add its exact key here (matching is exact and case-sensitive).
10
+ */
11
+ const SECRET_KEYS = [
12
+ 'password',
13
+ 'newPassword',
14
+ 'currentPassword',
15
+ 'passwordHash',
16
+ 'token',
17
+ 'accessToken',
18
+ 'refreshToken',
19
+ 'access_token',
20
+ 'refresh_token',
21
+ 'secret',
22
+ 'clientSecret',
23
+ 'apiKey',
24
+ 'api_key',
25
+ 'authorization',
26
+ 'cookie',
27
+ ];
28
+
29
+ /** Secret headers (same list as observability/sentry.ts SECRET_HEADERS), raw and under the `req` serializer. */
30
+ const SECRET_HEADERS = ['authorization', 'cookie', 'set-cookie', 'proxy-authorization', 'x-api-key', 'x-origin-verify'];
31
+
32
+ /**
33
+ * pino redact paths. A `*` matches exactly ONE level (pino has no "any depth"
34
+ * wildcard), so every key is listed at depths 0 to 3 explicitly; deeper keys
35
+ * are not covered. Measured cost: a few microseconds per log line.
36
+ */
37
+ export const REDACT_PATHS: string[] = [
38
+ ...SECRET_HEADERS.flatMap((h) => [`req.headers["${h}"]`, `headers["${h}"]`]),
39
+ ...SECRET_KEYS.flatMap((k) => [k, `*.${k}`, `*.*.${k}`, `*.*.*.${k}`]),
40
+ ];
41
+
4
42
  export const logger = pino({
5
43
  level: env.LOG_LEVEL,
6
- // Never let secrets reach the logs. Covers auth/cookie headers (raw and under
7
- // the `req` serializer) plus any password/token/secret field at any depth.
8
- // `remove: true` drops the key entirely rather than emitting "[Redacted]".
44
+ // Never let secrets reach the logs (REDACT_PATHS above). `remove: true` drops
45
+ // the key entirely rather than emitting "[Redacted]".
9
46
  redact: {
10
- paths: [
11
- 'req.headers.authorization',
12
- 'req.headers.cookie',
13
- 'headers.authorization',
14
- 'headers.cookie',
15
- '*.password',
16
- '*.token',
17
- '*.secret',
18
- ],
47
+ paths: REDACT_PATHS,
19
48
  remove: true,
20
49
  },
21
50
  ...(env.NODE_ENV !== 'production' && {