create-tigra 3.3.0 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +151 -0
- package/README.md +264 -56
- package/bin/create-tigra.js +497 -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 +5 -3
- 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/README.md +79 -0
- 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/README.md +92 -21
- 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/README.md +108 -0
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +66 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +81 -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,8 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sending email through Resend.
|
|
3
|
+
*
|
|
4
|
+
* - A send gives up after 10 s. The Resend SDK calls fetch with no timeout, so
|
|
5
|
+
* a hung Resend used to hold the request that sends (forgot-password waits
|
|
6
|
+
* for it) open for Node's ~5 minute default. Callers catch and log failures.
|
|
7
|
+
* - Recipient addresses are logged masked ('an***@example.com'): enough to
|
|
8
|
+
* trace one email while debugging, never the full address in the logs.
|
|
9
|
+
* - RESEND_BASE_URL (read by the SDK) points sends at a local stub in tests.
|
|
10
|
+
*/
|
|
1
11
|
import { Resend } from 'resend';
|
|
2
12
|
import { env } from '@config/env.js';
|
|
3
13
|
import { logger } from '@libs/logger.js';
|
|
4
14
|
import { InternalError } from '@shared/errors/errors.js';
|
|
5
15
|
|
|
16
|
+
const SEND_TIMEOUT_MS = 10_000;
|
|
17
|
+
|
|
6
18
|
let resendClient: Resend | null = null;
|
|
7
19
|
|
|
8
20
|
function getResendClient(): Resend {
|
|
@@ -15,26 +27,51 @@ function getResendClient(): Resend {
|
|
|
15
27
|
return resendClient;
|
|
16
28
|
}
|
|
17
29
|
|
|
30
|
+
/**
|
|
31
|
+
* An address as it may appear in logs: the first two characters of the local
|
|
32
|
+
* part (one if it has only one), then *** and the domain. Anything that is not
|
|
33
|
+
* an address becomes '***'.
|
|
34
|
+
*/
|
|
35
|
+
export function maskEmail(address: string): string {
|
|
36
|
+
const at = typeof address === 'string' ? address.lastIndexOf('@') : -1;
|
|
37
|
+
if (at < 1 || at === address.length - 1) return '***';
|
|
38
|
+
const local = address.slice(0, at);
|
|
39
|
+
return `${local.slice(0, local.length === 1 ? 1 : 2)}***@${address.slice(at + 1)}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
18
42
|
interface SendEmailOptions {
|
|
19
43
|
to: string;
|
|
20
44
|
subject: string;
|
|
21
45
|
html: string;
|
|
22
46
|
}
|
|
23
47
|
|
|
48
|
+
class EmailTimeout extends Error {}
|
|
49
|
+
|
|
24
50
|
export async function sendEmail({ to, subject, html }: SendEmailOptions): Promise<void> {
|
|
25
51
|
const client = getResendClient();
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
to,
|
|
30
|
-
subject,
|
|
31
|
-
html,
|
|
52
|
+
let timer: NodeJS.Timeout | undefined;
|
|
53
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
54
|
+
timer = setTimeout(() => reject(new EmailTimeout()), SEND_TIMEOUT_MS);
|
|
32
55
|
});
|
|
33
56
|
|
|
34
|
-
|
|
35
|
-
|
|
57
|
+
let result: Awaited<ReturnType<typeof client.emails.send>>;
|
|
58
|
+
try {
|
|
59
|
+
// The fetch may still finish in the background; we stop waiting for it.
|
|
60
|
+
result = await Promise.race([client.emails.send({ from: env.RESEND_FROM_EMAIL, to, subject, html }), timeout]);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error instanceof EmailTimeout) {
|
|
63
|
+
logger.error({ to: maskEmail(to), timeoutMs: SEND_TIMEOUT_MS }, '[EMAIL] Sending timed out');
|
|
64
|
+
throw new InternalError('Email send timed out');
|
|
65
|
+
}
|
|
66
|
+
throw error;
|
|
67
|
+
} finally {
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (result.error) {
|
|
72
|
+
logger.error({ emailError: result.error.message, to: maskEmail(to) }, '[EMAIL] Failed to send email');
|
|
36
73
|
throw new InternalError('Failed to send email');
|
|
37
74
|
}
|
|
38
75
|
|
|
39
|
-
logger.info({ to }, '[EMAIL] Email sent successfully');
|
|
76
|
+
logger.info({ to: maskEmail(to) }, '[EMAIL] Email sent successfully');
|
|
40
77
|
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The global error handler: every thrown error becomes the standard envelope
|
|
3
|
+
* ({ success: false, error: { code, message, ... } }). Register it before the
|
|
4
|
+
* routes (src/app.ts). Kept in its own module so tests can mount it on a small
|
|
5
|
+
* Fastify instance (src/libs/__tests__/error-handler.test.ts).
|
|
6
|
+
*
|
|
7
|
+
* Order matters:
|
|
8
|
+
* 1. AppError: our typed errors keep their status and code (plus
|
|
9
|
+
* retryAfterSeconds and fields when they carry them).
|
|
10
|
+
* 2. Wrong input (route schema or ZodError): 422 VALIDATION_FAILED with the
|
|
11
|
+
* field list, never the values (libs/validation-errors.ts).
|
|
12
|
+
* 3. Other 4xx from Fastify or a plugin (malformed JSON, body too large,
|
|
13
|
+
* rate limit, multipart limits): their status, a mapped code and a fixed or
|
|
14
|
+
* Fastify message.
|
|
15
|
+
* 4. Anything else: logged with its stack, sent to Sentry (a no-op unless
|
|
16
|
+
* configured), and answered with a generic 500 that reveals nothing.
|
|
17
|
+
*/
|
|
18
|
+
import type { FastifyError, FastifyInstance } from 'fastify';
|
|
19
|
+
import { logger } from '@libs/logger.js';
|
|
20
|
+
import { Sentry } from '@libs/observability/sentry.js';
|
|
21
|
+
import { fieldsFromSchemaValidation, fieldsFromZodIssues, validationError } from '@libs/validation-errors.js';
|
|
22
|
+
import { isAppError } from '@shared/errors/AppError.js';
|
|
23
|
+
import { errorResponse } from '@shared/responses/successResponse.js';
|
|
24
|
+
|
|
25
|
+
/** @fastify/multipart's limit errors other than a too-large file (all 413). */
|
|
26
|
+
const MULTIPART_LIMIT_CODES = new Set(['FST_PARTS_LIMIT', 'FST_FIELDS_LIMIT', 'FST_FILES_LIMIT']);
|
|
27
|
+
|
|
28
|
+
/** A ZodError thrown by `schema.parse()` in a handler (duck-typed: no instanceof across zod copies). */
|
|
29
|
+
function zodIssues(error: unknown): ReadonlyArray<{ path: ReadonlyArray<PropertyKey>; message: string }> | null {
|
|
30
|
+
if (!(error instanceof Error) || error.name !== 'ZodError') return null;
|
|
31
|
+
const issues = (error as { issues?: unknown }).issues;
|
|
32
|
+
return Array.isArray(issues) ? issues : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function registerErrorHandler(app: FastifyInstance): void {
|
|
36
|
+
app.setErrorHandler((error: FastifyError, request, reply) => {
|
|
37
|
+
// A multipart limit hit while a FILE part is already being read: the plugin
|
|
38
|
+
// destroys that file stream, so the handler's toBuffer() rejects with a bare
|
|
39
|
+
// "Premature close" (no status) instead of FST_FIELDS_LIMIT and the like.
|
|
40
|
+
// Typical case: many fields, then the file. On a multipart request that is
|
|
41
|
+
// a limit hit; a client that hung up mid-upload lands here too, but nobody
|
|
42
|
+
// is left to read the answer. Without this it would be a logged 500.
|
|
43
|
+
if (error.code === 'ERR_STREAM_PREMATURE_CLOSE' && request.isMultipart?.()) {
|
|
44
|
+
return reply.status(413).send(errorResponse('MULTIPART_LIMIT', 'Too many form fields or files in this upload'));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// AppError — our typed errors (use duck-type check to avoid instanceof issues)
|
|
48
|
+
if (isAppError(error)) {
|
|
49
|
+
return reply
|
|
50
|
+
.status(error.statusCode)
|
|
51
|
+
.send(errorResponse(error.code, error.message, error.retryAfterSeconds, error.fields));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Wrong input caught by a route schema: `validation` holds the items and
|
|
55
|
+
// `validationContext` the request part (body, querystring, params, headers).
|
|
56
|
+
if (error.validation) {
|
|
57
|
+
const fail = validationError(fieldsFromSchemaValidation(error.validation, error.validationContext));
|
|
58
|
+
return reply.status(fail.statusCode).send(errorResponse(fail.code, fail.message, undefined, fail.fields));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Wrong input caught by `schema.parse()` inside a handler.
|
|
62
|
+
const issues = zodIssues(error);
|
|
63
|
+
if (issues) {
|
|
64
|
+
const fail = validationError(fieldsFromZodIssues(issues));
|
|
65
|
+
return reply.status(fail.statusCode).send(errorResponse(fail.code, fail.message, undefined, fail.fields));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Fastify plugin errors (malformed JSON, file size, rate limiting, etc.)
|
|
69
|
+
// These have statusCode properties but aren't AppError instances
|
|
70
|
+
if (error.statusCode && error.statusCode >= 400 && error.statusCode < 500) {
|
|
71
|
+
// Too many parts, fields or files in one multipart upload (MULTIPART_LIMITS
|
|
72
|
+
// in libs/storage/file-validator.ts). 413 like a too-large file, but with
|
|
73
|
+
// its own code so the client does not tell the user their file is too big.
|
|
74
|
+
if (MULTIPART_LIMIT_CODES.has(error.code)) {
|
|
75
|
+
return reply
|
|
76
|
+
.status(413)
|
|
77
|
+
.send(errorResponse('MULTIPART_LIMIT', 'Too many form fields or files in this upload'));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Map common Fastify error codes to user-friendly messages
|
|
81
|
+
const errorCodeMap: Record<number, { code: string; message: string }> = {
|
|
82
|
+
413: { code: 'FILE_TOO_LARGE', message: 'File size exceeds the maximum allowed limit' },
|
|
83
|
+
429: { code: 'RATE_LIMIT_EXCEEDED', message: 'Too many requests. Please try again later' },
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const errorInfo = errorCodeMap[error.statusCode] || {
|
|
87
|
+
code: 'BAD_REQUEST',
|
|
88
|
+
message: error.message || 'Bad request',
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
return reply.status(error.statusCode).send(errorResponse(errorInfo.code, errorInfo.message));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Unexpected error — capture in Sentry (safe no-op when SDK uninitialized),
|
|
95
|
+
// then log and return a generic 500. reqId ties the event to the log line.
|
|
96
|
+
const requestId = request.id || 'unknown';
|
|
97
|
+
Sentry.captureException(error, { extra: { reqId: requestId } });
|
|
98
|
+
logger.error(
|
|
99
|
+
{
|
|
100
|
+
err: error,
|
|
101
|
+
requestId,
|
|
102
|
+
url: request.url,
|
|
103
|
+
method: request.method,
|
|
104
|
+
stack: error.stack,
|
|
105
|
+
},
|
|
106
|
+
`Unhandled error [${requestId}]: ${error.message}`,
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
return reply.status(500).send(errorResponse('INTERNAL_ERROR', 'Internal server error'));
|
|
110
|
+
});
|
|
111
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { FastifyInstance } from 'fastify';
|
|
2
|
+
import { successResponse } from '@shared/responses/successResponse.js';
|
|
3
|
+
import { performHealthCheck, checkReadiness, checkLiveness } from '@libs/monitoring.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The public probes, for uptime monitors, load balancers and Docker:
|
|
7
|
+
*
|
|
8
|
+
* - GET /api/v1/health: overall status only ({ status }); 200 healthy or
|
|
9
|
+
* degraded, 503 unhealthy (database down). Anyone can call it, so it says
|
|
10
|
+
* nothing about the internals: no response times, memory, uptime, versions,
|
|
11
|
+
* and no hint that Redis (and with it rate limits and IP blocks) is down
|
|
12
|
+
* beyond "degraded". The full report is admin-only: GET /api/v1/admin/health.
|
|
13
|
+
* - GET /api/v1/ready: { ready, timestamp }; 503 while the database is down.
|
|
14
|
+
* - GET /api/v1/live: { alive, timestamp }; the Dockerfile HEALTHCHECK.
|
|
15
|
+
*
|
|
16
|
+
* All three are in MONITORING_PATHS (libs/rate-limiting.ts): never rate
|
|
17
|
+
* limited or IP-blocked, and not request-logged. /health and /ready share one
|
|
18
|
+
* cached database check (libs/monitoring.ts), so probing them costs at most
|
|
19
|
+
* one query per 5 s.
|
|
20
|
+
*/
|
|
21
|
+
export function registerHealthRoutes(app: FastifyInstance): void {
|
|
22
|
+
app.get('/api/v1/health', { config: { rateLimit: false } }, async (_request, reply) => {
|
|
23
|
+
const { status } = await performHealthCheck();
|
|
24
|
+
const statusCode = status === 'unhealthy' ? 503 : 200;
|
|
25
|
+
const message =
|
|
26
|
+
status === 'healthy'
|
|
27
|
+
? 'All systems operational'
|
|
28
|
+
: status === 'degraded'
|
|
29
|
+
? 'Some systems degraded'
|
|
30
|
+
: 'System unhealthy';
|
|
31
|
+
return reply.status(statusCode).send(successResponse(message, { status }));
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
app.get('/api/v1/ready', { config: { rateLimit: false } }, async (_request, reply) => {
|
|
35
|
+
const ready = await checkReadiness();
|
|
36
|
+
return reply.status(ready ? 200 : 503).send(
|
|
37
|
+
successResponse(ready ? 'Service is ready' : 'Service not ready', {
|
|
38
|
+
ready,
|
|
39
|
+
timestamp: new Date().toISOString(),
|
|
40
|
+
}),
|
|
41
|
+
);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
app.get('/api/v1/live', { config: { rateLimit: false } }, (_request, reply) => {
|
|
45
|
+
const alive = checkLiveness();
|
|
46
|
+
return reply.status(alive ? 200 : 503).send(
|
|
47
|
+
successResponse(alive ? 'Service is alive' : 'Service not alive', {
|
|
48
|
+
alive,
|
|
49
|
+
timestamp: new Date().toISOString(),
|
|
50
|
+
}),
|
|
51
|
+
);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
@@ -1,66 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbound HTTP.
|
|
3
|
+
*
|
|
4
|
+
* `httpClient` is for TRUSTED, hard-coded URLs (provider APIs, Cloudflare's IP
|
|
5
|
+
* list). A URL that came from a user must go through `safeHttpClient`
|
|
6
|
+
* (libs/safe-http.ts), which refuses internal addresses.
|
|
7
|
+
*
|
|
8
|
+
* Both are built by `createHttpClient`, which adds:
|
|
9
|
+
* - logging of every call (debug) and failure (error), with the URL passed
|
|
10
|
+
* through redactUrl: credentials, query strings (API keys!) and bot tokens
|
|
11
|
+
* never reach the logs; bodies and headers are never logged;
|
|
12
|
+
* - a 10 MB cap on request and response bodies;
|
|
13
|
+
* - one error type for every failure, OutboundHttpError: unhandled it is the
|
|
14
|
+
* same generic 500 as before (code INTERNAL_ERROR, nothing upstream leaks),
|
|
15
|
+
* while the caller can read `kind` and `status` to handle "not found" or retry
|
|
16
|
+
* only timeouts.
|
|
17
|
+
*/
|
|
1
18
|
import axios, {
|
|
19
|
+
type AxiosError,
|
|
2
20
|
type AxiosInstance,
|
|
21
|
+
type CreateAxiosDefaults,
|
|
3
22
|
type InternalAxiosRequestConfig,
|
|
4
23
|
type AxiosResponse,
|
|
5
24
|
isAxiosError,
|
|
6
25
|
} from 'axios';
|
|
7
26
|
import { logger } from '@libs/logger.js';
|
|
27
|
+
import { redactUrl } from '@libs/url-safety.js';
|
|
8
28
|
import { InternalError } from '@shared/errors/errors.js';
|
|
9
29
|
|
|
10
30
|
const TIMEOUT_MS = 30_000;
|
|
31
|
+
/** Largest request or response body any outbound call may carry. */
|
|
32
|
+
export const MAX_BODY_BYTES = 10 * 1024 * 1024;
|
|
11
33
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
headers: {
|
|
15
|
-
'Content-Type': 'application/json',
|
|
16
|
-
Accept: 'application/json',
|
|
17
|
-
},
|
|
18
|
-
});
|
|
34
|
+
/** Error code our own guards put on a refused request (libs/safe-http.ts). */
|
|
35
|
+
export const OUTBOUND_BLOCKED = 'OUTBOUND_BLOCKED';
|
|
19
36
|
|
|
20
|
-
|
|
21
|
-
httpClient.interceptors.request.use(
|
|
22
|
-
(config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
|
|
23
|
-
logger.debug(
|
|
24
|
-
{ method: config.method?.toUpperCase(), url: config.url, baseURL: config.baseURL },
|
|
25
|
-
'[HTTP] Outbound request',
|
|
26
|
-
);
|
|
27
|
-
return config;
|
|
28
|
-
},
|
|
29
|
-
(error: unknown): never => {
|
|
30
|
-
logger.error({ err: error }, '[HTTP] Request setup failed');
|
|
31
|
-
throw new InternalError('Outbound HTTP request could not be constructed');
|
|
32
|
-
},
|
|
33
|
-
);
|
|
37
|
+
export type OutboundFailureKind = 'http' | 'timeout' | 'network' | 'blocked' | 'too-large';
|
|
34
38
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
if (
|
|
50
|
-
|
|
39
|
+
/**
|
|
40
|
+
* Every outbound failure. Extends InternalError with the SAME code and message,
|
|
41
|
+
* so an unhandled one answers the same generic 500 as before. `status` is the
|
|
42
|
+
* upstream HTTP status when there was a response; `cause` keeps the original
|
|
43
|
+
* error for the logs (pino logs only a cause's message and stack).
|
|
44
|
+
*/
|
|
45
|
+
export class OutboundHttpError extends InternalError {
|
|
46
|
+
readonly kind: OutboundFailureKind;
|
|
47
|
+
readonly status?: number;
|
|
48
|
+
|
|
49
|
+
constructor(kind: OutboundFailureKind, options: { status?: number; cause?: unknown } = {}) {
|
|
50
|
+
super('Outbound HTTP request failed');
|
|
51
|
+
this.kind = kind;
|
|
52
|
+
this.status = options.status;
|
|
53
|
+
if (options.cause !== undefined) {
|
|
54
|
+
Object.defineProperty(this, 'cause', { value: options.cause, enumerable: false });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** True when this error, or one it wraps, was refused by our own guards. */
|
|
60
|
+
function wasBlocked(error: unknown): boolean {
|
|
61
|
+
let current: unknown = error;
|
|
62
|
+
for (let depth = 0; depth < 5 && current; depth++) {
|
|
63
|
+
if ((current as { code?: unknown }).code === OUTBOUND_BLOCKED) return true;
|
|
64
|
+
current = (current as { cause?: unknown }).cause;
|
|
65
|
+
}
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function failureKind(error: AxiosError): OutboundFailureKind {
|
|
70
|
+
if (wasBlocked(error)) return 'blocked';
|
|
71
|
+
if (error.response) return 'http';
|
|
72
|
+
if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') return 'timeout';
|
|
73
|
+
if (typeof error.message === 'string' && error.message.includes('maxContentLength')) return 'too-large';
|
|
74
|
+
if (typeof error.message === 'string' && error.message.includes('maxBodyLength')) return 'too-large';
|
|
75
|
+
return 'network';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** URLs as they may be logged. */
|
|
79
|
+
const safeUrl = (url: string | undefined): string | undefined => (url === undefined ? undefined : redactUrl(url));
|
|
80
|
+
|
|
81
|
+
/** An axios instance with our logging, size caps and error type. */
|
|
82
|
+
export function createHttpClient(config: CreateAxiosDefaults = {}): AxiosInstance {
|
|
83
|
+
const client = axios.create({
|
|
84
|
+
timeout: TIMEOUT_MS,
|
|
85
|
+
maxContentLength: MAX_BODY_BYTES,
|
|
86
|
+
maxBodyLength: MAX_BODY_BYTES,
|
|
87
|
+
headers: {
|
|
88
|
+
'Content-Type': 'application/json',
|
|
89
|
+
Accept: 'application/json',
|
|
90
|
+
},
|
|
91
|
+
...config,
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
// Request interceptor — log every outbound call
|
|
95
|
+
client.interceptors.request.use(
|
|
96
|
+
(requestConfig: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
|
|
97
|
+
logger.debug(
|
|
51
98
|
{
|
|
52
|
-
method:
|
|
53
|
-
url:
|
|
54
|
-
|
|
55
|
-
message: error.message,
|
|
99
|
+
method: requestConfig.method?.toUpperCase(),
|
|
100
|
+
url: safeUrl(requestConfig.url),
|
|
101
|
+
baseURL: safeUrl(requestConfig.baseURL),
|
|
56
102
|
},
|
|
57
|
-
'[HTTP] Outbound request
|
|
103
|
+
'[HTTP] Outbound request',
|
|
58
104
|
);
|
|
59
|
-
|
|
105
|
+
return requestConfig;
|
|
106
|
+
},
|
|
107
|
+
(error: unknown): never => {
|
|
108
|
+
// A guard registered after this interceptor (it runs first) refused the
|
|
109
|
+
// request: keep its typed error, do not turn it into a setup failure.
|
|
110
|
+
if (error instanceof OutboundHttpError) throw error;
|
|
111
|
+
logger.error({ err: error }, '[HTTP] Request setup failed');
|
|
112
|
+
throw new InternalError('Outbound HTTP request could not be constructed');
|
|
113
|
+
},
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
// Response interceptor — log responses and turn every failure into OutboundHttpError
|
|
117
|
+
client.interceptors.response.use(
|
|
118
|
+
(response: AxiosResponse): AxiosResponse => {
|
|
119
|
+
logger.debug(
|
|
120
|
+
{
|
|
121
|
+
method: response.config.method?.toUpperCase(),
|
|
122
|
+
url: safeUrl(response.config.url),
|
|
123
|
+
status: response.status,
|
|
124
|
+
},
|
|
125
|
+
'[HTTP] Outbound response',
|
|
126
|
+
);
|
|
127
|
+
return response;
|
|
128
|
+
},
|
|
129
|
+
(error: unknown): never => {
|
|
130
|
+
// Already ours (a guard refused the request before axios sent it).
|
|
131
|
+
if (error instanceof OutboundHttpError) {
|
|
132
|
+
logger.error({ kind: error.kind }, '[HTTP] Outbound request refused');
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
if (isAxiosError(error)) {
|
|
136
|
+
logger.error(
|
|
137
|
+
{
|
|
138
|
+
method: error.config?.method?.toUpperCase(),
|
|
139
|
+
url: safeUrl(error.config?.url),
|
|
140
|
+
status: error.response?.status,
|
|
141
|
+
message: error.message,
|
|
142
|
+
},
|
|
143
|
+
'[HTTP] Outbound request failed',
|
|
144
|
+
);
|
|
145
|
+
throw new OutboundHttpError(failureKind(error), { status: error.response?.status, cause: error });
|
|
146
|
+
}
|
|
60
147
|
logger.error({ err: error }, '[HTTP] Unexpected outbound error');
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
148
|
+
throw new OutboundHttpError('network', { cause: error });
|
|
149
|
+
},
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
return client;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** For trusted, hard-coded URLs only. User-supplied URLs: safeHttpClient (libs/safe-http.ts). */
|
|
156
|
+
const httpClient: AxiosInstance = createHttpClient();
|
|
65
157
|
|
|
66
158
|
export { httpClient };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one canonical spelling of an IP address. Pure (no env, no I/O), so both
|
|
3
|
+
* the visitor-address code (libs/client-ip.ts, which re-exports it) and the IP
|
|
4
|
+
* block list (libs/ip-block.ts) can use it: a block an admin types in must be
|
|
5
|
+
* the same string as the key the visitor's requests produce.
|
|
6
|
+
*/
|
|
7
|
+
import { isIP } from 'node:net';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Canonical form of an address so one visitor always maps to one key, and an admin's IP
|
|
11
|
+
* block matches however the address was written:
|
|
12
|
+
* - IPv4-mapped IPv6 (`::ffff:203.0.113.7`, or its hex spelling `::ffff:cb00:7107`)
|
|
13
|
+
* becomes plain IPv4;
|
|
14
|
+
* - other IPv6 gets the one standard spelling (lower case, zeros compressed:
|
|
15
|
+
* `2001:0DB8:0000::0001` → `2001:db8::1`);
|
|
16
|
+
* - an IPv6 with a zone id (`fe80::1%eth0`, link-local only) is just lower-cased.
|
|
17
|
+
* Returns undefined for anything that is not an IP literal.
|
|
18
|
+
*/
|
|
19
|
+
export function normalizeIp(value: string | undefined): string | undefined {
|
|
20
|
+
if (!value) return undefined;
|
|
21
|
+
let ip = value.trim();
|
|
22
|
+
if (ip.toLowerCase().startsWith('::ffff:') && isIP(ip.slice(7)) === 4) ip = ip.slice(7);
|
|
23
|
+
const family = isIP(ip);
|
|
24
|
+
if (family === 0) return undefined;
|
|
25
|
+
return family === 4 ? ip : canonicalIpv6(ip);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The WHATWG URL parser's IPv6 serialization, with hex IPv4-mapped turned into IPv4. */
|
|
29
|
+
function canonicalIpv6(ip: string): string {
|
|
30
|
+
if (ip.includes('%')) return ip.toLowerCase(); // a zone id: the URL parser refuses it
|
|
31
|
+
const host = new URL(`http://[${ip}]/`).hostname.slice(1, -1);
|
|
32
|
+
const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host);
|
|
33
|
+
if (!mapped) return host;
|
|
34
|
+
const high = parseInt(mapped[1], 16);
|
|
35
|
+
const low = parseInt(mapped[2], 16);
|
|
36
|
+
return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
|
|
37
|
+
}
|