create-tigra 4.1.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +4 -1
- package/bin/create-tigra.js +68 -73
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +33 -59
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +18 -18
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +10 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +1 -24
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
- package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
- package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
- package/modules/metrics/performance.md +2 -2
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
- package/modules/metrics/server/metrics.collector.ts +6 -3
- package/modules/metrics/server/metrics.routes.ts +1 -2
- package/modules/metrics/server/metrics.service.ts +6 -2
- package/package.json +1 -1
- package/template/AGENTS.md +4 -3
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/package-lock.json +51 -51
- package/template/client/package.json +2 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -6,6 +6,7 @@ import { UnauthorizedError, ForbiddenError, BadRequestError } from '@shared/erro
|
|
|
6
6
|
import { clearAuthCookies } from '@libs/cookies.js';
|
|
7
7
|
import { assertAccountCanSignIn } from '@libs/account-status.js';
|
|
8
8
|
import { parseDurationMs } from '@libs/duration.js';
|
|
9
|
+
import { preventPrivateCaching } from '@libs/private-cache.js';
|
|
9
10
|
import type { JwtPayload, UserRole } from '@shared/types/index.js';
|
|
10
11
|
|
|
11
12
|
// Re-export so existing consumers of `parseDurationMs` from '@libs/auth.js'
|
|
@@ -37,15 +38,16 @@ export function generateRefreshToken(): string {
|
|
|
37
38
|
return uuidv4();
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
export function getRefreshTokenExpiresAt(): Date {
|
|
41
|
+
export function getRefreshTokenExpiresAt(now: Date = new Date()): Date {
|
|
41
42
|
const ms = parseDurationMs(env.JWT_REFRESH_EXPIRY, 7 * 24 * 60 * 60 * 1000);
|
|
42
|
-
return new Date(
|
|
43
|
+
return new Date(now.getTime() + ms);
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
export async function authenticate(
|
|
46
47
|
request: FastifyRequest,
|
|
47
48
|
reply: FastifyReply,
|
|
48
49
|
): Promise<void> {
|
|
50
|
+
preventPrivateCaching(reply);
|
|
49
51
|
try {
|
|
50
52
|
await request.jwtVerify();
|
|
51
53
|
} catch {
|
|
@@ -112,13 +114,15 @@ export async function authenticate(
|
|
|
112
114
|
*/
|
|
113
115
|
export async function optionalAuth(
|
|
114
116
|
request: FastifyRequest,
|
|
115
|
-
|
|
117
|
+
reply: FastifyReply,
|
|
116
118
|
): Promise<void> {
|
|
117
119
|
try {
|
|
118
120
|
await request.jwtVerify();
|
|
119
121
|
} catch {
|
|
120
122
|
// Not authenticated — that's okay for optional auth
|
|
123
|
+
return;
|
|
121
124
|
}
|
|
125
|
+
preventPrivateCaching(reply);
|
|
122
126
|
}
|
|
123
127
|
|
|
124
128
|
export function authorize(...roles: UserRole[]) {
|
|
@@ -136,6 +140,36 @@ export function authorize(...roles: UserRole[]) {
|
|
|
136
140
|
};
|
|
137
141
|
}
|
|
138
142
|
|
|
143
|
+
type AdminAuthorization = { allowed: true } | { allowed: false; error: unknown };
|
|
144
|
+
const adminAuthorization = new WeakMap<FastifyRequest, AdminAuthorization>();
|
|
145
|
+
|
|
146
|
+
/** A request qualifies only after the admin scope verifies its live session and current role. */
|
|
147
|
+
export function isAuthorizedAdminRequest(request: FastifyRequest): boolean {
|
|
148
|
+
return adminAuthorization.get(request)?.allowed === true;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Install only inside the admin route plugin, including its optional routes. */
|
|
152
|
+
export function registerAdminAuthorization(app: FastifyInstance): void {
|
|
153
|
+
const requireAdmin = authorize('ADMIN');
|
|
154
|
+
// Scoped onRequest hooks run before route-level rate limiting. Save failures
|
|
155
|
+
// until preValidation so denied requests still go through the existing quota.
|
|
156
|
+
app.addHook('onRequest', async (request, reply) => {
|
|
157
|
+
try {
|
|
158
|
+
await authenticate(request, reply);
|
|
159
|
+
await requireAdmin(request, reply);
|
|
160
|
+
adminAuthorization.set(request, { allowed: true });
|
|
161
|
+
} catch (error) {
|
|
162
|
+
adminAuthorization.set(request, { allowed: false, error });
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
app.addHook('preValidation', async (request) => {
|
|
167
|
+
const decision = adminAuthorization.get(request);
|
|
168
|
+
if (!decision) throw new UnauthorizedError('Authentication required');
|
|
169
|
+
if (!decision.allowed) throw decision.error;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
139
173
|
/**
|
|
140
174
|
* Middleware: resolves targetUserId from the authenticated user's JWT.
|
|
141
175
|
* Used for /users/me routes.
|
|
@@ -2,6 +2,7 @@ import type { FastifyReply } from 'fastify';
|
|
|
2
2
|
import { env } from '@config/env.js';
|
|
3
3
|
import { parseDurationMs } from '@libs/duration.js';
|
|
4
4
|
import { logger } from '@libs/logger.js';
|
|
5
|
+
import { preventPrivateCaching } from '@libs/private-cache.js';
|
|
5
6
|
|
|
6
7
|
const isProduction = env.NODE_ENV === 'production';
|
|
7
8
|
|
|
@@ -71,14 +72,27 @@ const REFRESH_TOKEN_PATH = '/api/v1/auth';
|
|
|
71
72
|
* Older versions of this template scoped the token cookies to COOKIE_DOMAIN.
|
|
72
73
|
* Browsers that still hold those would send two access_token cookies after an
|
|
73
74
|
* upgrade (the old domain-wide one can win and break auth), so whenever we set
|
|
74
|
-
* or clear tokens we also expire
|
|
75
|
-
*
|
|
75
|
+
* or clear tokens we also expire domain-wide copies on scopes that the API host
|
|
76
|
+
* can serve. Configured previous domains cover changes to COOKIE_DOMAIN.
|
|
76
77
|
*/
|
|
77
78
|
function expireLegacyDomainTokenCookies(reply: FastifyReply): void {
|
|
78
|
-
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
79
|
+
const host = reply.request.hostname.toLowerCase();
|
|
80
|
+
const current = sessionIndicatorDomain?.toLowerCase().replace(/^\./, '');
|
|
81
|
+
const domains = [...(sessionIndicatorDomain ? [sessionIndicatorDomain] : []), ...env.COOKIE_LEGACY_DOMAINS];
|
|
82
|
+
const seen = new Set<string>();
|
|
83
|
+
for (const domain of domains) {
|
|
84
|
+
const normalized = domain.toLowerCase().replace(/^\./, '');
|
|
85
|
+
if (seen.has(normalized) || (host !== normalized && !host.endsWith('.' + normalized))) continue;
|
|
86
|
+
seen.add(normalized);
|
|
87
|
+
const legacy = { httpOnly: true, secure: isProduction, sameSite: TOKEN_SAME_SITE, domain };
|
|
88
|
+
reply.clearCookie('access_token', { ...legacy, path: ACCESS_TOKEN_PATH });
|
|
89
|
+
reply.clearCookie('refresh_token', { ...legacy, path: REFRESH_TOKEN_PATH });
|
|
90
|
+
if (normalized !== current) clearSessionMarker(reply, domain);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function clearSessionMarker(reply: FastifyReply, domain?: string): void {
|
|
95
|
+
reply.clearCookie('auth_session', { secure: isProduction, sameSite: SESSION_SAME_SITE, domain, path: '/' });
|
|
82
96
|
}
|
|
83
97
|
|
|
84
98
|
export function setAuthCookies(
|
|
@@ -86,6 +100,7 @@ export function setAuthCookies(
|
|
|
86
100
|
accessToken: string,
|
|
87
101
|
refreshToken: string,
|
|
88
102
|
): void {
|
|
103
|
+
preventPrivateCaching(reply);
|
|
89
104
|
warnIfPlainHttp(reply);
|
|
90
105
|
expireLegacyDomainTokenCookies(reply);
|
|
91
106
|
|
|
@@ -107,6 +122,7 @@ export function setAuthCookies(
|
|
|
107
122
|
|
|
108
123
|
// Non-sensitive session indicator visible to the Next.js proxy and client JS.
|
|
109
124
|
// Lets the proxy distinguish "never logged in" from "access token expired but session alive."
|
|
125
|
+
if (sessionIndicatorDomain) clearSessionMarker(reply);
|
|
110
126
|
reply.setCookie('auth_session', '1', {
|
|
111
127
|
httpOnly: false,
|
|
112
128
|
secure: isProduction,
|
|
@@ -118,6 +134,7 @@ export function setAuthCookies(
|
|
|
118
134
|
}
|
|
119
135
|
|
|
120
136
|
export function clearAuthCookies(reply: FastifyReply): void {
|
|
137
|
+
preventPrivateCaching(reply);
|
|
121
138
|
expireLegacyDomainTokenCookies(reply);
|
|
122
139
|
|
|
123
140
|
reply.clearCookie('access_token', {
|
|
@@ -134,11 +151,6 @@ export function clearAuthCookies(reply: FastifyReply): void {
|
|
|
134
151
|
path: REFRESH_TOKEN_PATH,
|
|
135
152
|
});
|
|
136
153
|
|
|
137
|
-
reply
|
|
138
|
-
|
|
139
|
-
secure: isProduction,
|
|
140
|
-
sameSite: SESSION_SAME_SITE,
|
|
141
|
-
domain: sessionIndicatorDomain,
|
|
142
|
-
path: '/',
|
|
143
|
-
});
|
|
154
|
+
clearSessionMarker(reply);
|
|
155
|
+
if (sessionIndicatorDomain) clearSessionMarker(reply, sessionIndicatorDomain);
|
|
144
156
|
}
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* Rules that keep it from leaking which accounts exist:
|
|
20
20
|
* - Call it BEFORE looking the user up, so unknown addresses are counted exactly
|
|
21
21
|
* like real ones and the 429 says nothing about the account.
|
|
22
|
-
* - The counter key is a SHA-256 of the address, so
|
|
22
|
+
* - The counter key is a SHA-256 of the address, so quota keys hold no raw emails.
|
|
23
23
|
*
|
|
24
24
|
* Redis down → the email is allowed (fail open), like the other limiters.
|
|
25
25
|
*/
|
|
@@ -41,6 +41,15 @@ export function emailQuotaKey(email: string, bucket: EmailQuotaBucket = 'public'
|
|
|
41
41
|
return EMAIL_QUOTA_PREFIX[bucket] + createHash('sha256').update(email.trim().toLowerCase()).digest('hex');
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
export function emailQuotaExceeded(ttlMs: number): TooManyRequestsError {
|
|
45
|
+
const seconds = Math.max(1, Math.ceil(ttlMs / 1000));
|
|
46
|
+
return new TooManyRequestsError(
|
|
47
|
+
`Too many emails were sent to this address. Try again in ${describeWait(seconds)}.`,
|
|
48
|
+
'EMAIL_RATE_LIMITED',
|
|
49
|
+
seconds,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
44
53
|
/**
|
|
45
54
|
* Count one email to `email` in `bucket`. Throws 429 EMAIL_RATE_LIMITED (with
|
|
46
55
|
* retryAfterSeconds) once that counter is over its quota for the window.
|
|
@@ -65,10 +74,5 @@ export async function consumeEmailQuota(email: string, bucket: EmailQuotaBucket
|
|
|
65
74
|
logger.warn('[EMAIL-QUOTA] Redis unavailable, sending without the per-address cap');
|
|
66
75
|
return;
|
|
67
76
|
}
|
|
68
|
-
|
|
69
|
-
throw new TooManyRequestsError(
|
|
70
|
-
`Too many emails were sent to this address. Try again in ${describeWait(seconds)}.`,
|
|
71
|
-
'EMAIL_RATE_LIMITED',
|
|
72
|
-
seconds,
|
|
73
|
-
);
|
|
77
|
+
throw emailQuotaExceeded(ttlMs);
|
|
74
78
|
}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Sending email through Resend.
|
|
3
3
|
*
|
|
4
|
-
* - A send gives up after 10 s.
|
|
5
|
-
*
|
|
6
|
-
* for it) open for Node's ~5 minute default. Callers catch and log failures.
|
|
4
|
+
* - A send gives up after 10 s. Callers catch and log failures. Recovery
|
|
5
|
+
* runs in a background job and uses a provider deduplication key.
|
|
7
6
|
* - Recipient addresses are logged masked ('an***@example.com'): enough to
|
|
8
7
|
* trace one email while debugging, never the full address in the logs.
|
|
9
8
|
* - RESEND_BASE_URL (read by the SDK) points sends at a local stub in tests.
|
|
@@ -43,12 +42,14 @@ interface SendEmailOptions {
|
|
|
43
42
|
to: string;
|
|
44
43
|
subject: string;
|
|
45
44
|
html: string;
|
|
45
|
+
idempotencyKey?: string;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
class EmailTimeout extends Error {}
|
|
49
49
|
|
|
50
|
-
export async function sendEmail({ to, subject, html }: SendEmailOptions): Promise<void> {
|
|
50
|
+
export async function sendEmail({ to, subject, html, idempotencyKey }: SendEmailOptions): Promise<void> {
|
|
51
51
|
const client = getResendClient();
|
|
52
|
+
const recipient = idempotencyKey ? {} : { to: maskEmail(to) };
|
|
52
53
|
let timer: NodeJS.Timeout | undefined;
|
|
53
54
|
const timeout = new Promise<never>((_, reject) => {
|
|
54
55
|
timer = setTimeout(() => reject(new EmailTimeout()), SEND_TIMEOUT_MS);
|
|
@@ -57,10 +58,12 @@ export async function sendEmail({ to, subject, html }: SendEmailOptions): Promis
|
|
|
57
58
|
let result: Awaited<ReturnType<typeof client.emails.send>>;
|
|
58
59
|
try {
|
|
59
60
|
// The fetch may still finish in the background; we stop waiting for it.
|
|
60
|
-
|
|
61
|
+
const message = { from: env.RESEND_FROM_EMAIL, to, subject, html };
|
|
62
|
+
const delivery = idempotencyKey ? client.emails.send(message, { idempotencyKey }) : client.emails.send(message);
|
|
63
|
+
result = await Promise.race([delivery, timeout]);
|
|
61
64
|
} catch (error) {
|
|
62
65
|
if (error instanceof EmailTimeout) {
|
|
63
|
-
logger.error({
|
|
66
|
+
logger.error({ ...recipient, timeoutMs: SEND_TIMEOUT_MS }, '[EMAIL] Sending timed out');
|
|
64
67
|
throw new InternalError('Email send timed out');
|
|
65
68
|
}
|
|
66
69
|
throw error;
|
|
@@ -69,9 +72,9 @@ export async function sendEmail({ to, subject, html }: SendEmailOptions): Promis
|
|
|
69
72
|
}
|
|
70
73
|
|
|
71
74
|
if (result.error) {
|
|
72
|
-
logger.error(
|
|
75
|
+
logger.error(recipient, '[EMAIL] Failed to send email');
|
|
73
76
|
throw new InternalError('Failed to send email');
|
|
74
77
|
}
|
|
75
78
|
|
|
76
|
-
logger.info(
|
|
79
|
+
logger.info(recipient, '[EMAIL] Email sent successfully');
|
|
77
80
|
}
|
|
@@ -10,10 +10,9 @@
|
|
|
10
10
|
* 2. Wrong input (route schema or ZodError): 422 VALIDATION_FAILED with the
|
|
11
11
|
* field list, never the values (libs/validation-errors.ts).
|
|
12
12
|
* 3. Other 4xx from Fastify or a plugin (malformed JSON, body too large,
|
|
13
|
-
* rate limit, multipart limits): their status
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* configured), and answered with a generic 500 that reveals nothing.
|
|
13
|
+
* rate limit, multipart limits): their status and an application-owned message.
|
|
14
|
+
* 4. Anything else: logged by route and request ID, captured by Sentry when
|
|
15
|
+
* configured, and answered with a generic 500.
|
|
17
16
|
*/
|
|
18
17
|
import type { FastifyError, FastifyInstance } from 'fastify';
|
|
19
18
|
import { logger } from '@libs/logger.js';
|
|
@@ -46,6 +45,9 @@ export function registerErrorHandler(app: FastifyInstance): void {
|
|
|
46
45
|
|
|
47
46
|
// AppError — our typed errors (use duck-type check to avoid instanceof issues)
|
|
48
47
|
if (isAppError(error)) {
|
|
48
|
+
if (error.statusCode >= 500) {
|
|
49
|
+
Sentry.captureException(error, { tags: { reqId: request.id, route: request.routeOptions.url ?? '(unmatched)' } });
|
|
50
|
+
}
|
|
49
51
|
return reply
|
|
50
52
|
.status(error.statusCode)
|
|
51
53
|
.send(errorResponse(error.code, error.message, error.retryAfterSeconds, error.fields));
|
|
@@ -77,15 +79,17 @@ export function registerErrorHandler(app: FastifyInstance): void {
|
|
|
77
79
|
.send(errorResponse('MULTIPART_LIMIT', 'Too many form fields or files in this upload'));
|
|
78
80
|
}
|
|
79
81
|
|
|
80
|
-
//
|
|
82
|
+
// Parser messages can quote input. Return a fixed message for each known
|
|
83
|
+
// category and a fixed fallback for other client errors from plugins.
|
|
81
84
|
const errorCodeMap: Record<number, { code: string; message: string }> = {
|
|
82
85
|
413: { code: 'FILE_TOO_LARGE', message: 'File size exceeds the maximum allowed limit' },
|
|
86
|
+
415: { code: 'BAD_REQUEST', message: 'Unsupported media type' },
|
|
83
87
|
429: { code: 'RATE_LIMIT_EXCEEDED', message: 'Too many requests. Please try again later' },
|
|
84
88
|
};
|
|
85
89
|
|
|
86
|
-
const errorInfo = errorCodeMap[error.statusCode]
|
|
90
|
+
const errorInfo = errorCodeMap[error.statusCode] ?? {
|
|
87
91
|
code: 'BAD_REQUEST',
|
|
88
|
-
message:
|
|
92
|
+
message: 'Bad request',
|
|
89
93
|
};
|
|
90
94
|
|
|
91
95
|
return reply.status(error.statusCode).send(errorResponse(errorInfo.code, errorInfo.message));
|
|
@@ -94,16 +98,16 @@ export function registerErrorHandler(app: FastifyInstance): void {
|
|
|
94
98
|
// Unexpected error — capture in Sentry (safe no-op when SDK uninitialized),
|
|
95
99
|
// then log and return a generic 500. reqId ties the event to the log line.
|
|
96
100
|
const requestId = request.id || 'unknown';
|
|
97
|
-
|
|
101
|
+
const route = request.routeOptions.url ?? '(unmatched)';
|
|
102
|
+
Sentry.captureException(error, { tags: { reqId: requestId, route } });
|
|
98
103
|
logger.error(
|
|
99
104
|
{
|
|
100
105
|
err: error,
|
|
101
|
-
requestId,
|
|
102
|
-
|
|
106
|
+
reqId: requestId,
|
|
107
|
+
route,
|
|
103
108
|
method: request.method,
|
|
104
|
-
stack: error.stack,
|
|
105
109
|
},
|
|
106
|
-
|
|
110
|
+
'Unhandled request error',
|
|
107
111
|
);
|
|
108
112
|
|
|
109
113
|
return reply.status(500).send(errorResponse('INTERNAL_ERROR', 'Internal server error'));
|
|
@@ -13,8 +13,9 @@
|
|
|
13
13
|
* - one error type for every failure, OutboundHttpError: unhandled it is the
|
|
14
14
|
* same generic 500 as before (code INTERNAL_ERROR, nothing upstream leaks),
|
|
15
15
|
* while the caller can read `kind` and `status` to handle "not found" or retry
|
|
16
|
-
* only timeouts.
|
|
16
|
+
* only timeouts. Raw transport errors remain local to the interceptor.
|
|
17
17
|
*/
|
|
18
|
+
import { Readable } from 'node:stream';
|
|
18
19
|
import axios, {
|
|
19
20
|
type AxiosError,
|
|
20
21
|
type AxiosInstance,
|
|
@@ -39,20 +40,18 @@ export type OutboundFailureKind = 'http' | 'timeout' | 'network' | 'blocked' | '
|
|
|
39
40
|
/**
|
|
40
41
|
* Every outbound failure. Extends InternalError with the SAME code and message,
|
|
41
42
|
* so an unhandled one answers the same generic 500 as before. `status` is the
|
|
42
|
-
* upstream HTTP status when there was a response
|
|
43
|
-
* error
|
|
43
|
+
* upstream HTTP status when there was a response. Do not attach the original
|
|
44
|
+
* error: Axios keeps headers and payloads on it, and error serializers can
|
|
45
|
+
* follow even a non-enumerable cause.
|
|
44
46
|
*/
|
|
45
47
|
export class OutboundHttpError extends InternalError {
|
|
46
48
|
readonly kind: OutboundFailureKind;
|
|
47
49
|
readonly status?: number;
|
|
48
50
|
|
|
49
|
-
constructor(kind: OutboundFailureKind, options: { status?: number
|
|
51
|
+
constructor(kind: OutboundFailureKind, options: { status?: number } = {}) {
|
|
50
52
|
super('Outbound HTTP request failed');
|
|
51
53
|
this.kind = kind;
|
|
52
54
|
this.status = options.status;
|
|
53
|
-
if (options.cause !== undefined) {
|
|
54
|
-
Object.defineProperty(this, 'cause', { value: options.cause, enumerable: false });
|
|
55
|
-
}
|
|
56
55
|
}
|
|
57
56
|
}
|
|
58
57
|
|
|
@@ -70,11 +69,31 @@ function failureKind(error: AxiosError): OutboundFailureKind {
|
|
|
70
69
|
if (wasBlocked(error)) return 'blocked';
|
|
71
70
|
if (error.response) return 'http';
|
|
72
71
|
if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') return 'timeout';
|
|
72
|
+
if (error.code === 'ERR_CANCELED' && error.config?.signal instanceof AbortSignal
|
|
73
|
+
&& error.config.signal.reason?.name === 'TimeoutError') return 'timeout';
|
|
73
74
|
if (typeof error.message === 'string' && error.message.includes('maxContentLength')) return 'too-large';
|
|
74
75
|
if (typeof error.message === 'string' && error.message.includes('maxBodyLength')) return 'too-large';
|
|
75
76
|
return 'network';
|
|
76
77
|
}
|
|
77
78
|
|
|
79
|
+
/** Axios can fail a streaming body after the request promise has resolved. */
|
|
80
|
+
function safeResponseStream(source: Readable): Readable {
|
|
81
|
+
async function* readBody(): AsyncGenerator<Buffer> {
|
|
82
|
+
try {
|
|
83
|
+
yield* source;
|
|
84
|
+
} catch (error) {
|
|
85
|
+
const kind = isAxiosError(error) ? failureKind(error) : 'network';
|
|
86
|
+
throw new OutboundHttpError(kind);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const stream = Readable.from(readBody(), { objectMode: false });
|
|
90
|
+
// An aborted stream can fail before its caller starts reading. Preserve
|
|
91
|
+
// that failure for the iterator and release the source on early close.
|
|
92
|
+
source.on('error', () => {});
|
|
93
|
+
stream.once('close', () => source.destroy());
|
|
94
|
+
return stream;
|
|
95
|
+
}
|
|
96
|
+
|
|
78
97
|
/** URLs as they may be logged. */
|
|
79
98
|
const safeUrl = (url: string | undefined): string | undefined => (url === undefined ? undefined : redactUrl(url));
|
|
80
99
|
|
|
@@ -108,7 +127,7 @@ export function createHttpClient(config: CreateAxiosDefaults = {}): AxiosInstanc
|
|
|
108
127
|
// A guard registered after this interceptor (it runs first) refused the
|
|
109
128
|
// request: keep its typed error, do not turn it into a setup failure.
|
|
110
129
|
if (error instanceof OutboundHttpError) throw error;
|
|
111
|
-
logger.error(
|
|
130
|
+
logger.error('[HTTP] Request setup failed');
|
|
112
131
|
throw new InternalError('Outbound HTTP request could not be constructed');
|
|
113
132
|
},
|
|
114
133
|
);
|
|
@@ -124,6 +143,9 @@ export function createHttpClient(config: CreateAxiosDefaults = {}): AxiosInstanc
|
|
|
124
143
|
},
|
|
125
144
|
'[HTTP] Outbound response',
|
|
126
145
|
);
|
|
146
|
+
if (response.config.responseType === 'stream' && response.data instanceof Readable) {
|
|
147
|
+
response.data = safeResponseStream(response.data);
|
|
148
|
+
}
|
|
127
149
|
return response;
|
|
128
150
|
},
|
|
129
151
|
(error: unknown): never => {
|
|
@@ -133,19 +155,21 @@ export function createHttpClient(config: CreateAxiosDefaults = {}): AxiosInstanc
|
|
|
133
155
|
throw error;
|
|
134
156
|
}
|
|
135
157
|
if (isAxiosError(error)) {
|
|
158
|
+
const kind = failureKind(error);
|
|
159
|
+
const status = error.response?.status;
|
|
136
160
|
logger.error(
|
|
137
161
|
{
|
|
138
162
|
method: error.config?.method?.toUpperCase(),
|
|
139
163
|
url: safeUrl(error.config?.url),
|
|
140
|
-
status
|
|
141
|
-
|
|
164
|
+
status,
|
|
165
|
+
kind,
|
|
142
166
|
},
|
|
143
167
|
'[HTTP] Outbound request failed',
|
|
144
168
|
);
|
|
145
|
-
throw new OutboundHttpError(
|
|
169
|
+
throw new OutboundHttpError(kind, { status });
|
|
146
170
|
}
|
|
147
|
-
logger.error(
|
|
148
|
-
throw new OutboundHttpError('network'
|
|
171
|
+
logger.error('[HTTP] Unexpected outbound error');
|
|
172
|
+
throw new OutboundHttpError('network');
|
|
149
173
|
},
|
|
150
174
|
);
|
|
151
175
|
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* Design decisions:
|
|
9
9
|
* - DB is the source of truth for permanent blocks — survives Redis restarts
|
|
10
10
|
* - Redis is the hot cache — all runtime checks hit Redis only (O(1))
|
|
11
|
-
* -
|
|
11
|
+
* - Boot, reconnect, and admin edits publish complete DB snapshots to Redis
|
|
12
12
|
* - Fails open: if Redis is down, requests are NOT blocked (availability > security for rate limiting)
|
|
13
13
|
* - Lazy cleanup: expired auto-blocks are removed on check, no separate cleanup job needed
|
|
14
14
|
* - One spelling: every stored or removed block is the canonical form
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
* private/reserved address (a proxy or Docker address would block everyone).
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
+
import { randomUUID } from 'node:crypto';
|
|
22
23
|
import { env } from '@config/env.js';
|
|
23
24
|
import { prisma, isPrismaUniqueViolation } from '@libs/prisma.js';
|
|
24
25
|
import { getRedis } from '@libs/redis.js';
|
|
@@ -29,8 +30,32 @@ import { normalizeIp } from '@libs/ip-address.js';
|
|
|
29
30
|
|
|
30
31
|
// Redis keys
|
|
31
32
|
const BLOCKED_IPS_KEY = 'blocked_ips';
|
|
33
|
+
const BLOCKED_IPS_REVISION = 'blocked_ips:revision';
|
|
32
34
|
const AUTO_BLOCKED_KEY = 'auto_blocked_ips';
|
|
33
35
|
const VIOLATION_PREFIX = 'rl_violations:';
|
|
36
|
+
const BLOCK_SYNC_ATTEMPTS = 3;
|
|
37
|
+
|
|
38
|
+
// An expiry observed before a concurrent renewal is stale. Recheck and
|
|
39
|
+
// remove in Redis together so cleaning one IP cannot drop its active block.
|
|
40
|
+
const REMOVE_EXPIRED_BLOCK = `
|
|
41
|
+
local expiry = redis.call('ZSCORE', KEYS[1], ARGV[1])
|
|
42
|
+
if not expiry then return false end
|
|
43
|
+
if tonumber(expiry) > tonumber(ARGV[2]) then return expiry end
|
|
44
|
+
redis.call('ZREM', KEYS[1], ARGV[1])
|
|
45
|
+
return false
|
|
46
|
+
`;
|
|
47
|
+
|
|
48
|
+
// The revision check and replacement are atomic. Batch SADD to stay within
|
|
49
|
+
// Lua's argument stack even when a project has a large block list.
|
|
50
|
+
const REPLACE_PERMANENT_BLOCKS = `
|
|
51
|
+
if (redis.call('GET', KEYS[2]) or '') ~= ARGV[1] then return 0 end
|
|
52
|
+
redis.call('DEL', KEYS[1])
|
|
53
|
+
for i = 3, #ARGV, 500 do
|
|
54
|
+
redis.call('SADD', KEYS[1], unpack(ARGV, i, math.min(i + 499, #ARGV)))
|
|
55
|
+
end
|
|
56
|
+
redis.call('SET', KEYS[2], ARGV[2])
|
|
57
|
+
return 1
|
|
58
|
+
`;
|
|
34
59
|
|
|
35
60
|
// Auto-block thresholds — env-configurable (see .env.example).
|
|
36
61
|
// The threshold default is deliberately high (20): auto-block must catch
|
|
@@ -43,25 +68,30 @@ const AUTO_BLOCK_WINDOW_SECONDS = env.IP_AUTO_BLOCK_WINDOW_SECONDS; // sli
|
|
|
43
68
|
const AUTO_BLOCK_DURATION_SECONDS = env.IP_AUTO_BLOCK_DURATION_SECONDS; // block duration (default 3600 = 1 hour)
|
|
44
69
|
|
|
45
70
|
/**
|
|
46
|
-
*
|
|
47
|
-
*
|
|
71
|
+
* Publish the committed MySQL block list. Read the revision before fetching
|
|
72
|
+
* the rows so a concurrent publication forces a fresh snapshot. Admin edits
|
|
73
|
+
* use this same path after committing, even when two replicas edit one IP.
|
|
48
74
|
*/
|
|
49
75
|
export async function syncBlockedIpsToRedis(): Promise<void> {
|
|
50
76
|
try {
|
|
51
|
-
const blockedIps = await prisma.blockedIp.findMany({ select: { ip: true } });
|
|
52
|
-
|
|
53
77
|
const redis = getRedis();
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
78
|
+
for (let attempt = 0; attempt < BLOCK_SYNC_ATTEMPTS; attempt++) {
|
|
79
|
+
const revision = (await redis.get(BLOCKED_IPS_REVISION)) ?? '';
|
|
80
|
+
const blockedIps = await prisma.blockedIp.findMany({ select: { ip: true } });
|
|
81
|
+
const published = await redis.eval(
|
|
82
|
+
REPLACE_PERMANENT_BLOCKS, 2, BLOCKED_IPS_KEY, BLOCKED_IPS_REVISION,
|
|
83
|
+
revision, randomUUID(), ...blockedIps.map(({ ip }) => ip),
|
|
84
|
+
);
|
|
85
|
+
if (published === 1) {
|
|
86
|
+
logger.info(`[IP-BLOCK] Synced ${blockedIps.length} blocked IPs from DB to Redis`);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
60
89
|
}
|
|
61
|
-
|
|
62
|
-
|
|
90
|
+
// After the first conflict, contenders on the new revision read their
|
|
91
|
+
// snapshots after this caller's DB edit committed.
|
|
92
|
+
logger.debug('[IP-BLOCK] Concurrent replicas published the permanent block list');
|
|
63
93
|
} catch (error) {
|
|
64
|
-
logger.warn('[IP-BLOCK] Failed to sync blocked IPs from DB to Redis —
|
|
94
|
+
logger.warn('[IP-BLOCK] Failed to sync blocked IPs from DB to Redis — will retry on the next edit or reconnect');
|
|
65
95
|
logger.debug(error);
|
|
66
96
|
}
|
|
67
97
|
}
|
|
@@ -93,14 +123,13 @@ export async function getIpBlock(ip: string): Promise<IpBlock> {
|
|
|
93
123
|
|
|
94
124
|
// Check auto-block list (score = expiry Unix timestamp)
|
|
95
125
|
const score = await redis.zscore(AUTO_BLOCKED_KEY, ip);
|
|
96
|
-
if (score) {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
await redis.zrem(AUTO_BLOCKED_KEY, ip);
|
|
126
|
+
if (score === null) return { blocked: false };
|
|
127
|
+
const nowSeconds = Date.now() / 1000;
|
|
128
|
+
const expiry = Number(score) <= nowSeconds
|
|
129
|
+
? await redis.eval(REMOVE_EXPIRED_BLOCK, 1, AUTO_BLOCKED_KEY, ip, nowSeconds)
|
|
130
|
+
: score;
|
|
131
|
+
if (typeof expiry === 'string') {
|
|
132
|
+
return { blocked: true, permanent: false, retryAfterSeconds: Math.max(1, Math.ceil(Number(expiry) - nowSeconds)) };
|
|
104
133
|
}
|
|
105
134
|
|
|
106
135
|
return { blocked: false };
|
|
@@ -157,13 +186,7 @@ export async function blockIp(
|
|
|
157
186
|
throw error;
|
|
158
187
|
}
|
|
159
188
|
|
|
160
|
-
|
|
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
|
-
}
|
|
189
|
+
await syncBlockedIpsToRedis();
|
|
167
190
|
|
|
168
191
|
logger.info({ ip, blockedBy, reason }, '[IP-BLOCK] IP permanently blocked');
|
|
169
192
|
return blocked;
|
|
@@ -179,13 +202,12 @@ export async function unblockIp(rawIp: string): Promise<void> {
|
|
|
179
202
|
// Remove from DB
|
|
180
203
|
await prisma.blockedIp.deleteMany({ where: { ip } });
|
|
181
204
|
|
|
182
|
-
//
|
|
205
|
+
// Publish the permanent list and clear any automatic block for this address.
|
|
206
|
+
await syncBlockedIpsToRedis();
|
|
183
207
|
try {
|
|
184
|
-
|
|
185
|
-
await redis.srem(BLOCKED_IPS_KEY, ip);
|
|
186
|
-
await redis.zrem(AUTO_BLOCKED_KEY, ip);
|
|
208
|
+
await getRedis().zrem(AUTO_BLOCKED_KEY, ip);
|
|
187
209
|
} catch {
|
|
188
|
-
logger.warn({ ip }, '[IP-BLOCK] Failed to
|
|
210
|
+
logger.warn({ ip }, '[IP-BLOCK] Failed to clear automatic block — it will expire on schedule');
|
|
189
211
|
}
|
|
190
212
|
|
|
191
213
|
logger.info({ ip }, '[IP-BLOCK] IP unblocked');
|
|
@@ -39,6 +39,15 @@ export const REDACT_PATHS: string[] = [
|
|
|
39
39
|
...SECRET_KEYS.flatMap((k) => [k, `*.${k}`, `*.*.${k}`, `*.*.*.${k}`]),
|
|
40
40
|
];
|
|
41
41
|
|
|
42
|
+
/** Transport errors can hold request bodies, credentials and chained messages. */
|
|
43
|
+
function serializeError(error: unknown): { type: string; code?: string } {
|
|
44
|
+
if (!(error instanceof Error)) return { type: 'UnknownError' };
|
|
45
|
+
const type = /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(error.name) ? error.name : 'Error';
|
|
46
|
+
const code = 'code' in error && typeof error.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code)
|
|
47
|
+
? error.code : undefined;
|
|
48
|
+
return { type, code };
|
|
49
|
+
}
|
|
50
|
+
|
|
42
51
|
export const logger = pino({
|
|
43
52
|
level: env.LOG_LEVEL,
|
|
44
53
|
// Never let secrets reach the logs (REDACT_PATHS above). `remove: true` drops
|
|
@@ -47,6 +56,17 @@ export const logger = pino({
|
|
|
47
56
|
paths: REDACT_PATHS,
|
|
48
57
|
remove: true,
|
|
49
58
|
},
|
|
59
|
+
hooks: {
|
|
60
|
+
logMethod(args, method): void {
|
|
61
|
+
// Pino otherwise promotes a bare Error's message to the log line.
|
|
62
|
+
if (args[0] instanceof Error) {
|
|
63
|
+
const [error, ...rest] = args;
|
|
64
|
+
method.apply(this, [{ err: error }, ...rest]);
|
|
65
|
+
} else {
|
|
66
|
+
method.apply(this, args);
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
},
|
|
50
70
|
...(env.NODE_ENV !== 'production' && {
|
|
51
71
|
transport: {
|
|
52
72
|
target: 'pino-pretty',
|
|
@@ -59,16 +79,11 @@ export const logger = pino({
|
|
|
59
79
|
},
|
|
60
80
|
}),
|
|
61
81
|
serializers: {
|
|
82
|
+
err: serializeError,
|
|
62
83
|
req: (req) => ({
|
|
63
84
|
method: req.method,
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
params: req.params,
|
|
67
|
-
headers: {
|
|
68
|
-
host: req.headers.host,
|
|
69
|
-
'user-agent': req.headers['user-agent'],
|
|
70
|
-
'content-type': req.headers['content-type'],
|
|
71
|
-
},
|
|
85
|
+
route: req.routeOptions?.url ?? '(unmatched)',
|
|
86
|
+
id: req.id,
|
|
72
87
|
}),
|
|
73
88
|
res: (res) => ({
|
|
74
89
|
statusCode: res.statusCode,
|