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
|
@@ -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),
|
|
@@ -43,7 +43,7 @@ if (env.NODE_ENV === 'production') {
|
|
|
43
43
|
// Log all queries in development for debugging
|
|
44
44
|
if (env.NODE_ENV === 'development') {
|
|
45
45
|
baseClient.$on('query' as never, (e: { duration: number; query: string }) => {
|
|
46
|
-
logger.debug({ duration: e.duration
|
|
46
|
+
logger.debug({ duration: e.duration }, 'Database query');
|
|
47
47
|
});
|
|
48
48
|
}
|
|
49
49
|
|
|
@@ -16,6 +16,7 @@ import rateLimit from '@fastify/rate-limit';
|
|
|
16
16
|
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
|
17
17
|
import type { Redis } from 'ioredis';
|
|
18
18
|
import { DEFAULT_LIMIT, RATE_LIMIT_ENABLED } from '@config/rate-limit.config.js';
|
|
19
|
+
import { isAuthorizedAdminRequest } from '@libs/auth.js';
|
|
19
20
|
import { getClientIp } from '@libs/client-ip.js';
|
|
20
21
|
import { isAuthPath } from '@libs/auth-path.js';
|
|
21
22
|
import { recordRateLimitViolation } from '@libs/ip-block.js';
|
|
@@ -66,6 +67,9 @@ export async function registerRateLimiting(app: FastifyInstance, options: RateLi
|
|
|
66
67
|
timeWindow: DEFAULT_LIMIT.timeWindow,
|
|
67
68
|
...(options.redis ? { redis: options.redis, nameSpace: 'rl:' } : {}),
|
|
68
69
|
skipOnError: true,
|
|
70
|
+
// Only routes in the authenticated admin scope can set this decision. The
|
|
71
|
+
// allowlist skips both the quota and its onExceeded strike for those requests.
|
|
72
|
+
allowList: isAuthorizedAdminRequest,
|
|
69
73
|
// Key on the verified visitor address (one counter per real visitor, and never an
|
|
70
74
|
// address the visitor wrote itself) — see src/libs/client-ip.ts.
|
|
71
75
|
keyGenerator: (request: FastifyRequest) => getClientIp(request),
|
|
@@ -73,8 +73,8 @@ export interface RequestLineParts {
|
|
|
73
73
|
/**
|
|
74
74
|
* The URL without its query string or fragment. Queries carry search terms,
|
|
75
75
|
* email addresses and the like (`/admin/users?search=jane@example.com`), and
|
|
76
|
-
* links in emails carry tokens
|
|
77
|
-
* stay
|
|
76
|
+
* links in emails carry tokens. Request logs use registered route templates
|
|
77
|
+
* so submitted path segments stay out of the log as well.
|
|
78
78
|
*/
|
|
79
79
|
export function requestPath(url: string): string {
|
|
80
80
|
const end = url.search(/[?#]/);
|
|
@@ -149,7 +149,7 @@ export function logRequestLine(
|
|
|
149
149
|
const statusCode = reply.statusCode;
|
|
150
150
|
const parts: RequestLineParts = {
|
|
151
151
|
method: request.method,
|
|
152
|
-
url: request.url,
|
|
152
|
+
url: request.routeOptions.url ?? '(unmatched)',
|
|
153
153
|
statusCode,
|
|
154
154
|
statusMessage: reply.raw.statusMessage || '',
|
|
155
155
|
durationMs: request.startTime ? Date.now() - request.startTime : 0,
|
|
@@ -12,18 +12,21 @@
|
|
|
12
12
|
* is not public, and the socket then connects to exactly the addresses that
|
|
13
13
|
* were checked: a DNS answer cannot change between the check and the
|
|
14
14
|
* connection (DNS rebinding);
|
|
15
|
-
* - redirects: at most 3, each hop checked the same way
|
|
15
|
+
* - redirects: at most 3, each hop checked the same way. A different origin
|
|
16
|
+
* receives no caller-supplied headers and only bodyless GET/HEAD requests;
|
|
16
17
|
* - environment proxies are ignored (with a proxy the lookup would check the
|
|
17
18
|
* proxy, and the proxy would fetch the internal target for us);
|
|
18
|
-
* - 10 s
|
|
19
|
+
* - a 10 s total deadline and a 10 MB body cap, which callers may lower.
|
|
19
20
|
*
|
|
20
21
|
* A refused request throws OutboundHttpError with kind 'blocked' (a generic 500
|
|
21
22
|
* unless the caller handles it, e.g. as "this link is not allowed").
|
|
22
23
|
*/
|
|
23
24
|
import dns, { type LookupAddress } from 'node:dns';
|
|
25
|
+
import { Agent as HttpAgent } from 'node:http';
|
|
26
|
+
import { Agent as HttpsAgent } from 'node:https';
|
|
24
27
|
import { isIP } from 'node:net';
|
|
25
28
|
import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
|
|
26
|
-
import { createHttpClient, OutboundHttpError, OUTBOUND_BLOCKED } from '@libs/http.js';
|
|
29
|
+
import { createHttpClient, MAX_BODY_BYTES, OutboundHttpError, OUTBOUND_BLOCKED } from '@libs/http.js';
|
|
27
30
|
import { isForbiddenOutboundIp } from '@libs/url-safety.js';
|
|
28
31
|
|
|
29
32
|
const SAFE_TIMEOUT_MS = 10_000;
|
|
@@ -47,12 +50,16 @@ function literalIp(hostname: string): string | null {
|
|
|
47
50
|
}
|
|
48
51
|
|
|
49
52
|
/** Whether a target (protocol + hostname) may be connected to, before any DNS. */
|
|
50
|
-
function isAllowedTarget(
|
|
51
|
-
if (protocol !== 'http:' && protocol !== 'https:') return false;
|
|
52
|
-
const ip = literalIp(hostname);
|
|
53
|
+
function isAllowedTarget(target: URL, isForbidden: (ip: string) => boolean): boolean {
|
|
54
|
+
if ((target.protocol !== 'http:' && target.protocol !== 'https:') || target.username || target.password) return false;
|
|
55
|
+
const ip = literalIp(target.hostname);
|
|
53
56
|
return ip === null || !isForbidden(ip);
|
|
54
57
|
}
|
|
55
58
|
|
|
59
|
+
function boundedLimit(value: number | undefined, ceiling: number, minimum = 0): number {
|
|
60
|
+
return value !== undefined && Number.isSafeInteger(value) && value >= minimum ? Math.min(value, ceiling) : ceiling;
|
|
61
|
+
}
|
|
62
|
+
|
|
56
63
|
export interface SafeHttpOptions {
|
|
57
64
|
/** DNS resolver (tests inject one). */
|
|
58
65
|
resolve?: Resolve;
|
|
@@ -71,26 +78,59 @@ export function createSafeHttpClient({
|
|
|
71
78
|
return answers;
|
|
72
79
|
};
|
|
73
80
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
lookup,
|
|
79
|
-
// Redirect hops: an IP literal skips the lookup, so check it (and the protocol) here.
|
|
80
|
-
beforeRedirect: (options) => {
|
|
81
|
-
if (!isAllowedTarget(String(options.protocol), String(options.hostname), isForbidden)) throw blocked();
|
|
82
|
-
},
|
|
83
|
-
});
|
|
81
|
+
// Explicit agents also avoid Node's opt-in proxy-aware global agents.
|
|
82
|
+
const httpAgent = new HttpAgent();
|
|
83
|
+
const httpsAgent = new HttpsAgent();
|
|
84
|
+
const client = createHttpClient({ timeout: SAFE_TIMEOUT_MS, maxRedirects: MAX_REDIRECTS });
|
|
84
85
|
|
|
85
86
|
// First hop: refuse before anything is sent (an IP literal never reaches the lookup).
|
|
86
87
|
client.interceptors.request.use((config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
|
|
87
88
|
let target: URL;
|
|
88
89
|
try {
|
|
89
|
-
target = new URL(
|
|
90
|
+
target = new URL(client.getUri(config));
|
|
90
91
|
} catch {
|
|
91
92
|
throw new OutboundHttpError('blocked');
|
|
92
93
|
}
|
|
93
|
-
if (!isAllowedTarget(target
|
|
94
|
+
if (!isAllowedTarget(target, isForbidden)) throw new OutboundHttpError('blocked');
|
|
95
|
+
|
|
96
|
+
// The URL validated here is the one handed to the adapter. The transport
|
|
97
|
+
// and ceilings are policy, even when a caller changes Axios options.
|
|
98
|
+
config.url = target.href;
|
|
99
|
+
config.baseURL = undefined;
|
|
100
|
+
config.params = undefined;
|
|
101
|
+
config.adapter = 'http';
|
|
102
|
+
config.httpVersion = 1;
|
|
103
|
+
config.transport = undefined;
|
|
104
|
+
config.socketPath = undefined;
|
|
105
|
+
config.proxy = false;
|
|
106
|
+
config.httpAgent = httpAgent;
|
|
107
|
+
config.httpsAgent = httpsAgent;
|
|
108
|
+
config.lookup = lookup;
|
|
109
|
+
config.family = undefined;
|
|
110
|
+
config.headers.delete('Host');
|
|
111
|
+
config.maxRedirects = boundedLimit(config.maxRedirects, MAX_REDIRECTS);
|
|
112
|
+
config.maxBodyLength = boundedLimit(config.maxBodyLength, MAX_BODY_BYTES);
|
|
113
|
+
config.maxContentLength = boundedLimit(config.maxContentLength, MAX_BODY_BYTES);
|
|
114
|
+
config.timeout = boundedLimit(config.timeout, SAFE_TIMEOUT_MS, 1);
|
|
115
|
+
|
|
116
|
+
// Apply a wall-clock deadline as well as Axios's transport timeout. The
|
|
117
|
+
// signal starts before lookup and stays active across redirects and reads.
|
|
118
|
+
const deadline = AbortSignal.timeout(config.timeout);
|
|
119
|
+
config.signal = config.signal instanceof AbortSignal ? AbortSignal.any([config.signal, deadline]) : deadline;
|
|
120
|
+
|
|
121
|
+
let origin = target.origin;
|
|
122
|
+
const canRedirectAcrossOrigins = ['get', 'head'].includes(config.method?.toLowerCase() ?? 'get') && config.data == null;
|
|
123
|
+
config.beforeRedirect = (options): void => {
|
|
124
|
+
// IP literals bypass DNS, so reapply the destination policy at each hop.
|
|
125
|
+
const next = new URL(String(options.href));
|
|
126
|
+
if (!isAllowedTarget(next, isForbidden)) throw blocked();
|
|
127
|
+
if (next.origin !== origin) {
|
|
128
|
+
if (!canRedirectAcrossOrigins) throw blocked();
|
|
129
|
+
options.headers = {};
|
|
130
|
+
options.auth = undefined;
|
|
131
|
+
}
|
|
132
|
+
origin = next.origin;
|
|
133
|
+
};
|
|
94
134
|
return config;
|
|
95
135
|
});
|
|
96
136
|
|
|
@@ -4,11 +4,24 @@
|
|
|
4
4
|
* production, only inside a Docker container, and only when the folder is on
|
|
5
5
|
* the container's own disk (same device as "/") rather than a mounted volume.
|
|
6
6
|
*/
|
|
7
|
-
import
|
|
8
|
-
import {
|
|
7
|
+
import fs from 'fs/promises';
|
|
8
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
9
|
+
import { type DiskProbe, fileStorageService, uploadDirsOnContainerDisk } from '../file-storage.service.js';
|
|
9
10
|
|
|
10
11
|
const DIRS = ['/app/uploads/public', '/app/uploads/private'];
|
|
11
12
|
|
|
13
|
+
it('reports a storage error to the purge worker instead of treating the directory as absent', async () => {
|
|
14
|
+
const denied = Object.assign(new Error('cannot access media'), { code: 'EACCES' });
|
|
15
|
+
const stat = vi.spyOn(fs, 'stat').mockRejectedValue(denied);
|
|
16
|
+
const remove = vi.spyOn(fs, 'rm').mockRejectedValue(denied);
|
|
17
|
+
try {
|
|
18
|
+
await expect(fileStorageService.deleteUserMedia('a-local-fixture')).rejects.toMatchObject({ code: 'FILE_DELETE_FAILED' });
|
|
19
|
+
} finally {
|
|
20
|
+
stat.mockRestore();
|
|
21
|
+
remove.mockRestore();
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
|
|
12
25
|
/** A fake disk: "/" is device 1; `mounted` folders live on device 2. */
|
|
13
26
|
function disk({ container = true, mounted = [] as string[], broken = [] as string[] } = {}): DiskProbe {
|
|
14
27
|
return {
|