create-tigra 4.1.0 → 5.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/CHANGELOG.md +16 -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/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
|
@@ -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,
|
|
@@ -105,44 +105,67 @@ async function checkRedis(): Promise<CheckStatus> {
|
|
|
105
105
|
* interval, so an outage still shows within one probe.
|
|
106
106
|
*/
|
|
107
107
|
export const DEPENDENCY_CHECK_TTL_MS = 5_000;
|
|
108
|
+
const DEPENDENCY_CHECK_WAIT_MS = 1_000;
|
|
108
109
|
|
|
109
|
-
interface
|
|
110
|
-
|
|
111
|
-
redis: CheckStatus;
|
|
110
|
+
interface CheckedDependency {
|
|
111
|
+
result: CheckStatus;
|
|
112
112
|
checkedAt: number;
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
-
|
|
116
|
-
|
|
115
|
+
interface CachedDependency {
|
|
116
|
+
read(): Promise<CheckedDependency>;
|
|
117
|
+
reset(): void;
|
|
118
|
+
}
|
|
117
119
|
|
|
118
120
|
/**
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
*
|
|
122
|
-
* pending query per probe). Failures are cached too, so a down database is
|
|
123
|
-
* not retried by every probe. checkDatabase/checkRedis never throw.
|
|
121
|
+
* Share one real query or ping per dependency. Answer callers at the deadline,
|
|
122
|
+
* but keep ownership of the underlying operation until it actually completes.
|
|
123
|
+
* A stalled Redis check cannot delay a fresh database result or readiness.
|
|
124
124
|
*/
|
|
125
|
-
function
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
125
|
+
function cacheDependency(name: string, check: () => Promise<CheckStatus>): CachedDependency {
|
|
126
|
+
let cached: CheckedDependency | undefined;
|
|
127
|
+
let inFlight: Promise<CheckedDependency> | undefined;
|
|
128
|
+
return {
|
|
129
|
+
read(): Promise<CheckedDependency> {
|
|
130
|
+
if (cached && Date.now() - cached.checkedAt < DEPENDENCY_CHECK_TTL_MS) return Promise.resolve(cached);
|
|
131
|
+
if (inFlight) return inFlight;
|
|
132
|
+
|
|
133
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
134
|
+
const deadline = new Promise<CheckedDependency>((resolve) => {
|
|
135
|
+
timer = setTimeout(() => {
|
|
136
|
+
logger.warn({ dependency: name, timeoutMs: DEPENDENCY_CHECK_WAIT_MS }, 'Health check exceeded its deadline');
|
|
137
|
+
resolve({
|
|
138
|
+
result: { status: 'down', message: `${name} health check timed out`, responseTime: DEPENDENCY_CHECK_WAIT_MS },
|
|
139
|
+
checkedAt: Date.now(),
|
|
140
|
+
});
|
|
141
|
+
}, DEPENDENCY_CHECK_WAIT_MS);
|
|
142
|
+
timer.unref();
|
|
137
143
|
});
|
|
138
|
-
|
|
139
|
-
|
|
144
|
+
const actual = check().then((result) => ({ result, checkedAt: Date.now() }));
|
|
145
|
+
const pending = Promise.race([actual, deadline]);
|
|
146
|
+
inFlight = pending;
|
|
147
|
+
void actual.then((result) => {
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
if (inFlight !== pending) return;
|
|
150
|
+
cached = result;
|
|
151
|
+
inFlight = undefined;
|
|
152
|
+
});
|
|
153
|
+
return pending;
|
|
154
|
+
},
|
|
155
|
+
reset(): void {
|
|
156
|
+
cached = undefined;
|
|
157
|
+
inFlight = undefined;
|
|
158
|
+
},
|
|
159
|
+
};
|
|
140
160
|
}
|
|
141
161
|
|
|
162
|
+
const databaseCheck = cacheDependency('Database', checkDatabase);
|
|
163
|
+
const redisCheck = cacheDependency('Redis', checkRedis);
|
|
164
|
+
|
|
142
165
|
/** Forget the cached checks, so each test starts with a real check. */
|
|
143
166
|
export function resetHealthCacheForTests(): void {
|
|
144
|
-
|
|
145
|
-
|
|
167
|
+
databaseCheck.reset();
|
|
168
|
+
redisCheck.reset();
|
|
146
169
|
}
|
|
147
170
|
|
|
148
171
|
/** Heap use above this share of the heap LIMIT counts as degraded. */
|
|
@@ -235,11 +258,14 @@ export function shortCommit(raw: string | undefined): string | null {
|
|
|
235
258
|
const APP_VERSION = readAppVersion();
|
|
236
259
|
|
|
237
260
|
/**
|
|
238
|
-
* Full health report (admins only). Database and Redis
|
|
239
|
-
*
|
|
261
|
+
* Full health report (admins only). Database and Redis use their shared 5 s
|
|
262
|
+
* caches. Memory and uptime are read fresh.
|
|
240
263
|
*/
|
|
241
264
|
export async function performHealthCheck(): Promise<HealthCheckResult> {
|
|
242
|
-
const
|
|
265
|
+
const [databaseStatus, redisStatus] = await Promise.all([databaseCheck.read(), redisCheck.read()]);
|
|
266
|
+
const database = databaseStatus.result;
|
|
267
|
+
const redis = redisStatus.result;
|
|
268
|
+
const checkedAt = Math.max(databaseStatus.checkedAt, redisStatus.checkedAt);
|
|
243
269
|
const memory = checkMemory();
|
|
244
270
|
const uptime = checkUptime();
|
|
245
271
|
|
|
@@ -281,8 +307,8 @@ export async function performHealthCheck(): Promise<HealthCheckResult> {
|
|
|
281
307
|
* not. Shares the cached check with /health, so it adds no query of its own.
|
|
282
308
|
*/
|
|
283
309
|
export async function checkReadiness(): Promise<boolean> {
|
|
284
|
-
const {
|
|
285
|
-
return
|
|
310
|
+
const { result } = await databaseCheck.read();
|
|
311
|
+
return result.status !== 'down';
|
|
286
312
|
}
|
|
287
313
|
|
|
288
314
|
/**
|
|
@@ -14,77 +14,88 @@ import { logger } from '@libs/logger.js';
|
|
|
14
14
|
|
|
15
15
|
let initialized = false;
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
* Header names that must never leave the process (compared lowercase), and
|
|
24
|
-
* headers whose value is a URL that may carry a token in its query string.
|
|
25
|
-
* Keep in step with the client scrubber (client/src/lib/observability/sentry-scrub.ts).
|
|
26
|
-
*/
|
|
27
|
-
const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key', 'x-origin-verify']);
|
|
28
|
-
const URL_HEADERS = new Set(['referer', 'referrer']);
|
|
17
|
+
const URL_FIELDS = new Set([
|
|
18
|
+
'url', 'url.full', 'http.url', 'http.target', 'referer', 'referrer',
|
|
19
|
+
'http.request.header.referer', 'http.request.header.referrer', 'from', 'to',
|
|
20
|
+
]);
|
|
21
|
+
const HTTP_FIELDS = new Set(['http.request.method', 'http.method', 'http.response.status_code', 'http.status_code', 'status_code']);
|
|
22
|
+
const SAFE_REQUEST_HEADERS = new Set(['referer', 'referrer']);
|
|
29
23
|
|
|
30
|
-
/**
|
|
31
|
-
function
|
|
32
|
-
|
|
33
|
-
|
|
24
|
+
/** A raw URL can carry private path segments as well as query parameters. */
|
|
25
|
+
function safeUrl(url: string): string {
|
|
26
|
+
try {
|
|
27
|
+
const parsed = new URL(url);
|
|
28
|
+
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return parsed.origin;
|
|
29
|
+
} catch { /* Relative or malformed URL. */ }
|
|
30
|
+
return '(url omitted)';
|
|
34
31
|
}
|
|
35
32
|
|
|
36
|
-
/**
|
|
37
|
-
* Clean a free-form attribute bag (breadcrumb data, span data, trace data):
|
|
38
|
-
* strip queries from anything URL-like (url.full, http.target, referer
|
|
39
|
-
* attributes, …) and drop query/cookie/auth attributes entirely.
|
|
40
|
-
*/
|
|
33
|
+
/** Keep HTTP dimensions and sanitized URLs. Arbitrary bags may hold bodies or SQL. */
|
|
41
34
|
function scrubData(data: Record<string, unknown> | undefined): void {
|
|
42
35
|
if (!data) return;
|
|
43
|
-
for (const key of Object.
|
|
36
|
+
for (const [key, value] of Object.entries(data)) {
|
|
44
37
|
const lower = key.toLowerCase();
|
|
45
|
-
if (
|
|
38
|
+
if (typeof value === 'string' && URL_FIELDS.has(lower)) {
|
|
39
|
+
data[key] = safeUrl(value);
|
|
40
|
+
} else if (!HTTP_FIELDS.has(lower) || (typeof value !== 'number' && typeof value !== 'string')) {
|
|
46
41
|
delete data[key];
|
|
47
|
-
continue;
|
|
48
|
-
}
|
|
49
|
-
const value = data[key];
|
|
50
|
-
if (
|
|
51
|
-
typeof value === 'string' &&
|
|
52
|
-
(lower.includes('url') || lower.includes('referer') || lower.includes('target') || lower === 'from' || lower === 'to')
|
|
53
|
-
) {
|
|
54
|
-
data[key] = withoutQuery(value);
|
|
55
42
|
}
|
|
56
43
|
}
|
|
57
44
|
}
|
|
58
45
|
|
|
59
|
-
/**
|
|
60
|
-
* Remove request bodies, cookies, auth headers and query strings (including
|
|
61
|
-
* inside the Referer header, span/trace attributes and the transaction name)
|
|
62
|
-
* from an event before it is sent. Exported for tests.
|
|
63
|
-
*/
|
|
46
|
+
/** Shared privacy contract for the generated API server and Next.js app. */
|
|
64
47
|
export function scrubSentryEvent<T extends Event>(event: T): T {
|
|
48
|
+
delete event.user;
|
|
49
|
+
delete event.extra;
|
|
50
|
+
delete event.message;
|
|
51
|
+
delete event.logentry;
|
|
52
|
+
|
|
65
53
|
const request = event.request;
|
|
66
54
|
if (request) {
|
|
67
55
|
delete request.data;
|
|
68
56
|
delete request.cookies;
|
|
69
57
|
delete request.query_string;
|
|
70
|
-
|
|
58
|
+
delete request.env;
|
|
59
|
+
if (request.url) request.url = safeUrl(request.url);
|
|
71
60
|
if (request.headers) {
|
|
72
|
-
for (const name of Object.
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
else if (URL_HEADERS.has(lower)) request.headers[name] = withoutQuery(request.headers[name]);
|
|
61
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
62
|
+
if (SAFE_REQUEST_HEADERS.has(name.toLowerCase())) request.headers[name] = safeUrl(value);
|
|
63
|
+
else delete request.headers[name];
|
|
76
64
|
}
|
|
77
65
|
}
|
|
78
66
|
}
|
|
79
67
|
|
|
80
|
-
if (event.
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
68
|
+
if (event.tags) {
|
|
69
|
+
const { reqId, route } = event.tags;
|
|
70
|
+
event.tags = { reqId, route };
|
|
71
|
+
}
|
|
72
|
+
if (event.transaction && event.transaction_info?.source !== 'route') event.transaction = '(request)';
|
|
73
|
+
for (const exception of event.exception?.values ?? []) {
|
|
74
|
+
exception.value = 'Exception details omitted';
|
|
75
|
+
delete exception.mechanism?.data;
|
|
76
|
+
for (const frame of exception.stacktrace?.frames ?? []) {
|
|
77
|
+
delete frame.vars;
|
|
78
|
+
delete frame.abs_path;
|
|
79
|
+
delete frame.pre_context;
|
|
80
|
+
delete frame.context_line;
|
|
81
|
+
delete frame.post_context;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
for (const crumb of event.breadcrumbs ?? []) {
|
|
85
|
+
delete crumb.message;
|
|
86
|
+
scrubData(crumb.data as Record<string, unknown> | undefined);
|
|
87
|
+
}
|
|
88
|
+
for (const span of event.spans ?? []) {
|
|
89
|
+
// Descriptions can hold SQL or a path assembled from customer data.
|
|
90
|
+
delete span.description;
|
|
91
|
+
scrubData(span.data as Record<string, unknown> | undefined);
|
|
92
|
+
}
|
|
93
|
+
const trace = event.contexts?.trace;
|
|
94
|
+
if (event.contexts) event.contexts = trace ? { trace } : undefined;
|
|
95
|
+
scrubData(trace?.data as Record<string, unknown> | undefined);
|
|
85
96
|
return event;
|
|
86
|
-
}
|
|
87
|
-
|
|
97
|
+
}
|
|
98
|
+
|
|
88
99
|
/**
|
|
89
100
|
* Initialize Sentry only when a DSN is configured.
|
|
90
101
|
*
|
|
@@ -109,7 +120,12 @@ export function initSentry(): void {
|
|
|
109
120
|
sendDefaultPii: false,
|
|
110
121
|
// Don't even buffer incoming request bodies (default 'medium' = 10 KB,
|
|
111
122
|
// which would include login/register/password-change payloads).
|
|
112
|
-
integrations: [
|
|
123
|
+
integrations: [
|
|
124
|
+
Sentry.httpIntegration({ maxIncomingRequestBodySize: 'none' }),
|
|
125
|
+
// Keep tracing, but let our handler capture the exception with the route
|
|
126
|
+
// and request ID. An automatic capture wins the SDK's deduplication race.
|
|
127
|
+
Sentry.fastifyIntegration({ shouldHandleError: () => false }),
|
|
128
|
+
],
|
|
113
129
|
// Last line of defence for anything another integration still attaches.
|
|
114
130
|
beforeSend: (event) => scrubSentryEvent(event),
|
|
115
131
|
beforeSendTransaction: (event) => scrubSentryEvent(event),
|