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.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +72 -10
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +44 -13
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +81 -0
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -270
- package/template/server/.env.example.production +283 -242
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +176 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +0 -3
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -346
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -182
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +98 -7
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +38 -2
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/auth.ts +39 -10
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +53 -14
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -221
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +127 -41
- package/template/server/src/libs/observability/sentry.ts +1 -1
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +27 -1
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +94 -84
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +49 -10
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +66 -4
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +44 -44
- package/template/server/src/modules/auth/auth.schemas.ts +4 -2
- package/template/server/src/modules/auth/auth.service.ts +167 -96
- package/template/server/src/modules/auth/session.repo.ts +12 -0
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +23 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +3 -10
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- 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
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
//
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
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
|
|
7
|
-
// the
|
|
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' && {
|