create-tigra 3.2.0 → 3.3.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/lib/patchers/email-verification.patcher.js +93 -39
- package/modules/email-verification/server/verification.service.ts +38 -9
- package/package.json +1 -1
- package/template/client/src/features/auth/components/AuthInitializer.tsx +4 -2
- package/template/client/src/features/auth/components/LoginForm.tsx +5 -2
- package/template/client/src/features/auth/hooks/useAuth.ts +16 -6
- package/template/client/src/features/auth/types/auth.types.ts +3 -0
- package/template/client/src/instrumentation-client.ts +9 -1
- package/template/client/src/instrumentation.ts +6 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
- package/template/client/src/lib/utils/error.ts +5 -1
- package/template/client/src/lib/utils/security.ts +37 -0
- package/template/server/.env.example +5 -4
- package/template/server/.env.example.production +14 -8
- package/template/server/Dockerfile +5 -0
- package/template/server/prisma/schema.prisma +19 -3
- package/template/server/prisma/seed.ts +13 -5
- package/template/server/src/app.ts +11 -0
- package/template/server/src/config/env.ts +17 -6
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +58 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +72 -58
- package/template/server/src/libs/__tests__/auth.test.ts +77 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +62 -0
- package/template/server/src/libs/__tests__/redis.test.ts +23 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +80 -0
- package/template/server/src/libs/account-status.ts +52 -0
- package/template/server/src/libs/auth.ts +15 -5
- package/template/server/src/libs/cookies.ts +40 -12
- package/template/server/src/libs/ip-block.ts +3 -2
- package/template/server/src/libs/monitoring.ts +4 -1
- package/template/server/src/libs/observability/sentry.ts +80 -0
- package/template/server/src/libs/redis.ts +82 -18
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +84 -0
- package/template/server/src/libs/storage/file-storage.service.ts +21 -10
- package/template/server/src/libs/storage/image-optimizer.service.ts +67 -72
- package/template/server/src/modules/admin/admin.repo.ts +7 -3
- package/template/server/src/modules/admin/admin.service.ts +7 -3
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +136 -13
- package/template/server/src/modules/auth/auth.controller.ts +1 -1
- package/template/server/src/modules/auth/auth.repo.ts +20 -2
- package/template/server/src/modules/auth/auth.schemas.ts +1 -0
- package/template/server/src/modules/auth/auth.service.ts +30 -13
- package/template/server/src/modules/auth/session.repo.ts +0 -12
- package/template/server/src/modules/users/users.repo.ts +2 -0
- package/template/server/src/test/setup.ts +22 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Account status rules: one place that decides whether an existing, non-deleted
|
|
3
|
+
* account may hold a session.
|
|
4
|
+
*
|
|
5
|
+
* Two independent states, deliberately kept apart:
|
|
6
|
+
* - `isActive` — the admin ban switch. false = deactivated by an admin.
|
|
7
|
+
* - `emailVerifiedAt` — proof of email ownership. Required only while
|
|
8
|
+
* REQUIRE_USER_VERIFICATION is on.
|
|
9
|
+
*
|
|
10
|
+
* They used to share one flag (`isActive=false` meant "banned" OR "not
|
|
11
|
+
* verified yet"), which let a banned user re-activate themselves through the
|
|
12
|
+
* email-verification link. Every place that issues or honours a session
|
|
13
|
+
* (login, refresh, authenticate, verify-account) calls this helper so the rule
|
|
14
|
+
* cannot drift between them.
|
|
15
|
+
*
|
|
16
|
+
* Callers must run it only AFTER the user has proven who they are (password,
|
|
17
|
+
* valid token or refresh token): the distinct error codes would otherwise tell
|
|
18
|
+
* an anonymous caller whether an email is banned or unverified.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { env } from '@config/env.js';
|
|
22
|
+
import { ForbiddenError } from '@shared/errors/errors.js';
|
|
23
|
+
|
|
24
|
+
export const ACCOUNT_DEACTIVATED = 'ACCOUNT_DEACTIVATED';
|
|
25
|
+
export const EMAIL_NOT_VERIFIED = 'EMAIL_NOT_VERIFIED';
|
|
26
|
+
|
|
27
|
+
export interface AccountStatus {
|
|
28
|
+
isActive: boolean;
|
|
29
|
+
emailVerifiedAt: Date | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** True when the account still needs to verify its email before signing in. */
|
|
33
|
+
export function needsEmailVerification(user: Pick<AccountStatus, 'emailVerifiedAt'>): boolean {
|
|
34
|
+
return env.REQUIRE_USER_VERIFICATION && !user.emailVerifiedAt;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Throw a 403 when the account may not hold a session.
|
|
39
|
+
* The ban check runs first: a banned account must never be told to "verify",
|
|
40
|
+
* because verifying cannot (and must not) lift a ban.
|
|
41
|
+
*/
|
|
42
|
+
export function assertAccountCanSignIn(user: AccountStatus): void {
|
|
43
|
+
if (!user.isActive) {
|
|
44
|
+
throw new ForbiddenError(
|
|
45
|
+
'This account has been deactivated. Contact support if you think this is a mistake.',
|
|
46
|
+
ACCOUNT_DEACTIVATED,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
if (needsEmailVerification(user)) {
|
|
50
|
+
throw new ForbiddenError('Please verify your email address before signing in.', EMAIL_NOT_VERIFIED);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -4,6 +4,7 @@ import { env } from '@config/env.js';
|
|
|
4
4
|
import { prisma } from '@libs/prisma.js';
|
|
5
5
|
import { UnauthorizedError, ForbiddenError, BadRequestError } from '@shared/errors/errors.js';
|
|
6
6
|
import { clearAuthCookies } from '@libs/cookies.js';
|
|
7
|
+
import { assertAccountCanSignIn } from '@libs/account-status.js';
|
|
7
8
|
import { parseDurationMs } from '@libs/duration.js';
|
|
8
9
|
import type { JwtPayload, UserRole } from '@shared/types/index.js';
|
|
9
10
|
|
|
@@ -51,24 +52,33 @@ export async function authenticate(
|
|
|
51
52
|
throw new UnauthorizedError('Invalid or expired token');
|
|
52
53
|
}
|
|
53
54
|
|
|
54
|
-
// Verify user still exists, is
|
|
55
|
-
// When the session is definitively dead (user gone/deleted/
|
|
55
|
+
// Verify user still exists, is not banned/unverified, and not soft-deleted.
|
|
56
|
+
// When the session is definitively dead (user gone/deleted/banned), clear auth
|
|
56
57
|
// cookies on the response so the browser stops replaying stale credentials.
|
|
57
58
|
// Without this, middleware keeps seeing the (still-unexpired) JWT cookie and
|
|
58
59
|
// bounces /login → /dashboard → 401 → /login in an infinite loop.
|
|
59
60
|
const user = await prisma.user.findUnique({
|
|
60
61
|
where: { id: request.user.userId },
|
|
61
|
-
select: { isActive: true, deletedAt: true },
|
|
62
|
+
select: { isActive: true, emailVerifiedAt: true, deletedAt: true, role: true },
|
|
62
63
|
});
|
|
63
64
|
|
|
64
65
|
if (!user || user.deletedAt) {
|
|
65
66
|
clearAuthCookies(reply);
|
|
66
67
|
throw new UnauthorizedError('Account is deactivated or deleted');
|
|
67
68
|
}
|
|
68
|
-
|
|
69
|
+
try {
|
|
70
|
+
assertAccountCanSignIn(user);
|
|
71
|
+
} catch (error) {
|
|
69
72
|
clearAuthCookies(reply);
|
|
70
|
-
throw
|
|
73
|
+
throw error;
|
|
71
74
|
}
|
|
75
|
+
|
|
76
|
+
// The role decides authorization, so take it from the database, not from the
|
|
77
|
+
// token. A JWT keeps the role it was signed with until it expires (15 min by
|
|
78
|
+
// default); trusting it let a demoted admin keep admin rights for that window.
|
|
79
|
+
// Same query as above, so this costs nothing extra. authorize() and
|
|
80
|
+
// resolveTargetUser() read request.user.role after this runs.
|
|
81
|
+
request.user.role = user.role;
|
|
72
82
|
}
|
|
73
83
|
|
|
74
84
|
export async function optionalAuth(
|
|
@@ -9,23 +9,52 @@ const isProduction = env.NODE_ENV === 'production';
|
|
|
9
9
|
const isCrossOrigin = Boolean(env.COOKIE_DOMAIN);
|
|
10
10
|
const sameSitePolicy = isProduction && isCrossOrigin ? 'none' as const : 'strict' as const;
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
/**
|
|
13
|
+
* Cookie scope rules:
|
|
14
|
+
* - access_token / refresh_token are bearer credentials and are HOST-ONLY (no
|
|
15
|
+
* Domain attribute): the browser sends them only to the API host that set
|
|
16
|
+
* them. Only the API ever reads them — the client calls the API directly
|
|
17
|
+
* with credentials — so sharing them with every sibling subdomain would
|
|
18
|
+
* only leak live logins to hosts that don't need them (a CNAME'd help desk,
|
|
19
|
+
* another app on the same domain, a compromised subdomain).
|
|
20
|
+
* - auth_session ("1", no secret) is the one cookie that must be visible to
|
|
21
|
+
* the client host's Next.js middleware, so it alone uses COOKIE_DOMAIN
|
|
22
|
+
* (e.g. ".example.com" covers app.example.com + api.example.com).
|
|
23
|
+
*/
|
|
24
|
+
const sessionIndicatorDomain = env.COOKIE_DOMAIN || undefined;
|
|
14
25
|
|
|
15
26
|
const ACCESS_TOKEN_MAX_AGE_MS = parseDurationMs(env.JWT_ACCESS_EXPIRY, 15 * 60 * 1000);
|
|
16
27
|
const REFRESH_TOKEN_MAX_AGE_MS = parseDurationMs(env.JWT_REFRESH_EXPIRY, 7 * 24 * 60 * 60 * 1000);
|
|
17
28
|
|
|
29
|
+
const ACCESS_TOKEN_PATH = '/';
|
|
30
|
+
const REFRESH_TOKEN_PATH = '/api/v1/auth';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Older versions of this template scoped the token cookies to COOKIE_DOMAIN.
|
|
34
|
+
* Browsers that still hold those would send two access_token cookies after an
|
|
35
|
+
* upgrade (the old domain-wide one can win and break auth), so whenever we set
|
|
36
|
+
* or clear tokens we also expire any domain-wide copies. No-op without
|
|
37
|
+
* COOKIE_DOMAIN. Safe to keep: expiring a cookie that doesn't exist is harmless.
|
|
38
|
+
*/
|
|
39
|
+
function expireLegacyDomainTokenCookies(reply: FastifyReply): void {
|
|
40
|
+
if (!sessionIndicatorDomain) return;
|
|
41
|
+
const legacy = { httpOnly: true, secure: isProduction, sameSite: sameSitePolicy, domain: sessionIndicatorDomain };
|
|
42
|
+
reply.clearCookie('access_token', { ...legacy, path: ACCESS_TOKEN_PATH });
|
|
43
|
+
reply.clearCookie('refresh_token', { ...legacy, path: REFRESH_TOKEN_PATH });
|
|
44
|
+
}
|
|
45
|
+
|
|
18
46
|
export function setAuthCookies(
|
|
19
47
|
reply: FastifyReply,
|
|
20
48
|
accessToken: string,
|
|
21
49
|
refreshToken: string,
|
|
22
50
|
): void {
|
|
51
|
+
expireLegacyDomainTokenCookies(reply);
|
|
52
|
+
|
|
23
53
|
reply.setCookie('access_token', accessToken, {
|
|
24
54
|
httpOnly: true,
|
|
25
55
|
secure: isProduction,
|
|
26
56
|
sameSite: sameSitePolicy,
|
|
27
|
-
|
|
28
|
-
path: '/',
|
|
57
|
+
path: ACCESS_TOKEN_PATH,
|
|
29
58
|
maxAge: Math.floor(ACCESS_TOKEN_MAX_AGE_MS / 1000), // setCookie expects seconds
|
|
30
59
|
});
|
|
31
60
|
|
|
@@ -33,8 +62,7 @@ export function setAuthCookies(
|
|
|
33
62
|
httpOnly: true,
|
|
34
63
|
secure: isProduction,
|
|
35
64
|
sameSite: sameSitePolicy,
|
|
36
|
-
|
|
37
|
-
path: '/api/v1/auth',
|
|
65
|
+
path: REFRESH_TOKEN_PATH,
|
|
38
66
|
maxAge: Math.floor(REFRESH_TOKEN_MAX_AGE_MS / 1000),
|
|
39
67
|
});
|
|
40
68
|
|
|
@@ -44,34 +72,34 @@ export function setAuthCookies(
|
|
|
44
72
|
httpOnly: false,
|
|
45
73
|
secure: isProduction,
|
|
46
74
|
sameSite: sameSitePolicy,
|
|
47
|
-
domain:
|
|
75
|
+
domain: sessionIndicatorDomain,
|
|
48
76
|
path: '/',
|
|
49
77
|
maxAge: Math.floor(REFRESH_TOKEN_MAX_AGE_MS / 1000),
|
|
50
78
|
});
|
|
51
79
|
}
|
|
52
80
|
|
|
53
81
|
export function clearAuthCookies(reply: FastifyReply): void {
|
|
82
|
+
expireLegacyDomainTokenCookies(reply);
|
|
83
|
+
|
|
54
84
|
reply.clearCookie('access_token', {
|
|
55
85
|
httpOnly: true,
|
|
56
86
|
secure: isProduction,
|
|
57
87
|
sameSite: sameSitePolicy,
|
|
58
|
-
|
|
59
|
-
path: '/',
|
|
88
|
+
path: ACCESS_TOKEN_PATH,
|
|
60
89
|
});
|
|
61
90
|
|
|
62
91
|
reply.clearCookie('refresh_token', {
|
|
63
92
|
httpOnly: true,
|
|
64
93
|
secure: isProduction,
|
|
65
94
|
sameSite: sameSitePolicy,
|
|
66
|
-
|
|
67
|
-
path: '/api/v1/auth',
|
|
95
|
+
path: REFRESH_TOKEN_PATH,
|
|
68
96
|
});
|
|
69
97
|
|
|
70
98
|
reply.clearCookie('auth_session', {
|
|
71
99
|
httpOnly: false,
|
|
72
100
|
secure: isProduction,
|
|
73
101
|
sameSite: sameSitePolicy,
|
|
74
|
-
domain:
|
|
102
|
+
domain: sessionIndicatorDomain,
|
|
75
103
|
path: '/',
|
|
76
104
|
});
|
|
77
105
|
}
|
|
@@ -102,7 +102,7 @@ export async function blockIp(
|
|
|
102
102
|
ip: string,
|
|
103
103
|
blockedBy: string,
|
|
104
104
|
reason?: string,
|
|
105
|
-
): Promise<{ id: string; ip: string; reason: string | null; blockedBy: string; createdAt: Date }> {
|
|
105
|
+
): Promise<{ id: string; ip: string; reason: string | null; blockedBy: string | null; createdAt: Date }> {
|
|
106
106
|
// Write to DB (source of truth)
|
|
107
107
|
const existing = await prisma.blockedIp.findUnique({ where: { ip } });
|
|
108
108
|
if (existing) {
|
|
@@ -150,7 +150,8 @@ export async function unblockIp(ip: string): Promise<void> {
|
|
|
150
150
|
* List all currently blocked IPs (permanent from DB + active auto-blocks from Redis).
|
|
151
151
|
*/
|
|
152
152
|
export async function getBlockedIps(): Promise<{
|
|
153
|
-
|
|
153
|
+
// blockedBy is null once the admin who created the block has been purged.
|
|
154
|
+
permanent: { id: string; ip: string; reason: string | null; blockedBy: string | null; createdAt: Date }[];
|
|
154
155
|
autoBlocked: string[];
|
|
155
156
|
}> {
|
|
156
157
|
// Permanent blocks from DB (source of truth)
|
|
@@ -161,7 +161,10 @@ export async function performHealthCheck(): Promise<HealthCheckResult> {
|
|
|
161
161
|
status = 'unhealthy'; // Critical: DB is required
|
|
162
162
|
} else if (
|
|
163
163
|
database.status === 'degraded' ||
|
|
164
|
-
|
|
164
|
+
// Redis down is non-fatal (the app keeps serving and reconnects on its
|
|
165
|
+
// own), but rate limits, IP blocks and login lockout are off meanwhile, so
|
|
166
|
+
// monitoring must see it instead of a green "healthy".
|
|
167
|
+
redis.status !== 'up' ||
|
|
165
168
|
memory.status === 'degraded'
|
|
166
169
|
) {
|
|
167
170
|
status = 'degraded';
|
|
@@ -8,11 +8,83 @@
|
|
|
8
8
|
* Never hardcode a DSN here or anywhere — it comes only from the environment.
|
|
9
9
|
*/
|
|
10
10
|
import * as Sentry from '@sentry/node';
|
|
11
|
+
import type { Event } from '@sentry/node';
|
|
11
12
|
import { env } from '@config/env.js';
|
|
12
13
|
import { logger } from '@libs/logger.js';
|
|
13
14
|
|
|
14
15
|
let initialized = false;
|
|
15
16
|
|
|
17
|
+
/**
|
|
18
|
+
* Privacy rule for error tracking: Sentry gets the error, never the secrets
|
|
19
|
+
* around it. Same policy as the log redaction in libs/logger.ts — without it
|
|
20
|
+
* a 500 during login/register/password change would ship the plaintext
|
|
21
|
+
* password, the auth cookies and any token in the URL to a third party.
|
|
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']);
|
|
28
|
+
const URL_HEADERS = new Set(['referer', 'referrer']);
|
|
29
|
+
|
|
30
|
+
/** Drop the query string: reset/verify tokens and other secrets travel there. */
|
|
31
|
+
function withoutQuery(url: string): string {
|
|
32
|
+
const cut = url.search(/[?#]/);
|
|
33
|
+
return cut === -1 ? url : url.slice(0, cut);
|
|
34
|
+
}
|
|
35
|
+
|
|
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
|
+
*/
|
|
41
|
+
function scrubData(data: Record<string, unknown> | undefined): void {
|
|
42
|
+
if (!data) return;
|
|
43
|
+
for (const key of Object.keys(data)) {
|
|
44
|
+
const lower = key.toLowerCase();
|
|
45
|
+
if (lower.includes('query') || lower.includes('cookie') || lower.includes('authorization')) {
|
|
46
|
+
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
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
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
|
+
*/
|
|
64
|
+
export function scrubSentryEvent<T extends Event>(event: T): T {
|
|
65
|
+
const request = event.request;
|
|
66
|
+
if (request) {
|
|
67
|
+
delete request.data;
|
|
68
|
+
delete request.cookies;
|
|
69
|
+
delete request.query_string;
|
|
70
|
+
if (request.url) request.url = withoutQuery(request.url);
|
|
71
|
+
if (request.headers) {
|
|
72
|
+
for (const name of Object.keys(request.headers)) {
|
|
73
|
+
const lower = name.toLowerCase();
|
|
74
|
+
if (SECRET_HEADERS.has(lower)) delete request.headers[name];
|
|
75
|
+
else if (URL_HEADERS.has(lower)) request.headers[name] = withoutQuery(request.headers[name]);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (event.transaction) event.transaction = withoutQuery(event.transaction);
|
|
81
|
+
for (const crumb of event.breadcrumbs ?? []) scrubData(crumb.data as Record<string, unknown> | undefined);
|
|
82
|
+
for (const span of event.spans ?? []) scrubData(span.data as Record<string, unknown> | undefined);
|
|
83
|
+
scrubData(event.contexts?.trace?.data as Record<string, unknown> | undefined);
|
|
84
|
+
|
|
85
|
+
return event;
|
|
86
|
+
}
|
|
87
|
+
|
|
16
88
|
/**
|
|
17
89
|
* Initialize Sentry only when a DSN is configured.
|
|
18
90
|
*
|
|
@@ -33,6 +105,14 @@ export function initSentry(): void {
|
|
|
33
105
|
dsn: env.SENTRY_DSN,
|
|
34
106
|
tracesSampleRate: env.SENTRY_TRACES_SAMPLE_RATE,
|
|
35
107
|
environment: env.SENTRY_ENVIRONMENT,
|
|
108
|
+
// Never attach IPs/user identity automatically.
|
|
109
|
+
sendDefaultPii: false,
|
|
110
|
+
// Don't even buffer incoming request bodies (default 'medium' = 10 KB,
|
|
111
|
+
// which would include login/register/password-change payloads).
|
|
112
|
+
integrations: [Sentry.httpIntegration({ maxIncomingRequestBodySize: 'none' })],
|
|
113
|
+
// Last line of defence for anything another integration still attaches.
|
|
114
|
+
beforeSend: (event) => scrubSentryEvent(event),
|
|
115
|
+
beforeSendTransaction: (event) => scrubSentryEvent(event),
|
|
36
116
|
});
|
|
37
117
|
|
|
38
118
|
initialized = true;
|
|
@@ -2,38 +2,93 @@ import { Redis } from 'ioredis';
|
|
|
2
2
|
import { env } from '@config/env.js';
|
|
3
3
|
import { logger } from '@libs/logger.js';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Shared Redis client (rate limits, IP blocks, login lockout, reset tokens).
|
|
7
|
+
*
|
|
8
|
+
* Availability contract:
|
|
9
|
+
* - The connection reconnects FOREVER with capped backoff. It used to give up
|
|
10
|
+
* after REDIS_MAX_RETRIES attempts, which left a process permanently without
|
|
11
|
+
* rate limits, IP blocks and login lockout after any Redis blip longer than
|
|
12
|
+
* ~1 second, until someone restarted it.
|
|
13
|
+
* - While Redis is down, commands fail IMMEDIATELY (`enableOfflineQueue:
|
|
14
|
+
* false`) instead of queueing. Every caller already fails open on errors, so
|
|
15
|
+
* requests keep flowing without waiting ~10 s per command for a reconnect.
|
|
16
|
+
* - Logs say once when the connection is lost and once when it is back, not on
|
|
17
|
+
* every retry.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const RETRY_STEP_MS = 200;
|
|
21
|
+
const RETRY_MAX_DELAY_MS = 5000;
|
|
22
|
+
|
|
23
|
+
/** Backoff between reconnect attempts. Never returns null: we never give up. */
|
|
24
|
+
export function redisRetryDelay(attempt: number): number {
|
|
25
|
+
return Math.min(attempt * RETRY_STEP_MS, RETRY_MAX_DELAY_MS);
|
|
26
|
+
}
|
|
27
|
+
|
|
5
28
|
let redis: Redis | null = null;
|
|
29
|
+
let connectionLost = false;
|
|
30
|
+
let closingOnPurpose = false;
|
|
31
|
+
const readyListeners = new Set<() => void>();
|
|
32
|
+
|
|
33
|
+
const LOST_MESSAGE =
|
|
34
|
+
'[REDIS] Connection lost — retrying in the background; rate limits, IP blocks and login lockout fail open until it is back';
|
|
35
|
+
|
|
36
|
+
/** Log the outage once, whichever event (error or close) reports it first. */
|
|
37
|
+
function markConnectionLost(error?: Error): void {
|
|
38
|
+
if (closingOnPurpose) return;
|
|
39
|
+
if (!connectionLost) {
|
|
40
|
+
connectionLost = true;
|
|
41
|
+
logger.warn(error ? { err: error } : {}, LOST_MESSAGE);
|
|
42
|
+
} else if (error) {
|
|
43
|
+
logger.debug({ err: error }, '[REDIS] Still unavailable');
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Run `listener` every time the client becomes ready again after a reconnect
|
|
49
|
+
* (e.g. to restore state a restarted Redis lost). Returns an unsubscribe fn.
|
|
50
|
+
*/
|
|
51
|
+
export function onRedisReady(listener: () => void): () => void {
|
|
52
|
+
readyListeners.add(listener);
|
|
53
|
+
return () => readyListeners.delete(listener);
|
|
54
|
+
}
|
|
6
55
|
|
|
7
56
|
export function getRedis(): Redis {
|
|
8
57
|
if (!redis) {
|
|
58
|
+
closingOnPurpose = false;
|
|
9
59
|
redis = new Redis(env.REDIS_URL, {
|
|
60
|
+
// Retries for a single command; the connection itself retries forever.
|
|
10
61
|
maxRetriesPerRequest: env.REDIS_MAX_RETRIES,
|
|
11
62
|
connectTimeout: env.REDIS_CONNECT_TIMEOUT,
|
|
12
63
|
lazyConnect: true,
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
// Stop retrying after max retries
|
|
17
|
-
logger.error('[REDIS] Max retries reached, giving up');
|
|
18
|
-
return null;
|
|
19
|
-
}
|
|
20
|
-
const delay = Math.min(times * 50, 3000);
|
|
64
|
+
enableOfflineQueue: false,
|
|
65
|
+
retryStrategy: (times: number): number => {
|
|
66
|
+
const delay = redisRetryDelay(times);
|
|
21
67
|
logger.debug(`[REDIS] Retry attempt ${times}, waiting ${delay}ms`);
|
|
22
68
|
return delay;
|
|
23
69
|
},
|
|
24
70
|
});
|
|
25
71
|
|
|
26
|
-
redis.on('
|
|
27
|
-
|
|
72
|
+
redis.on('ready', () => {
|
|
73
|
+
if (connectionLost) {
|
|
74
|
+
connectionLost = false;
|
|
75
|
+
logger.info('[REDIS] Reconnected — Redis-backed protections are active again');
|
|
76
|
+
for (const listener of readyListeners) {
|
|
77
|
+
try {
|
|
78
|
+
listener();
|
|
79
|
+
} catch (error) {
|
|
80
|
+
logger.warn({ err: error }, '[REDIS] Ready listener failed');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
logger.info('[REDIS] Connection established');
|
|
85
|
+
}
|
|
28
86
|
});
|
|
29
87
|
|
|
30
|
-
redis.on('error', (error: Error) =>
|
|
31
|
-
logger.warn({ err: error }, '[REDIS] Connection error');
|
|
32
|
-
});
|
|
88
|
+
redis.on('error', (error: Error) => markConnectionLost(error));
|
|
33
89
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
});
|
|
90
|
+
// A close without an error (e.g. Redis restarted cleanly) is also an outage.
|
|
91
|
+
redis.on('close', () => markConnectionLost());
|
|
37
92
|
}
|
|
38
93
|
|
|
39
94
|
return redis;
|
|
@@ -45,7 +100,7 @@ export async function connectRedis(): Promise<boolean> {
|
|
|
45
100
|
await client.connect();
|
|
46
101
|
return true;
|
|
47
102
|
} catch (error) {
|
|
48
|
-
logger.warn('[REDIS]
|
|
103
|
+
logger.warn('[REDIS] Initial connection failed — server starts without Redis and keeps retrying in the background');
|
|
49
104
|
logger.debug(error);
|
|
50
105
|
return false;
|
|
51
106
|
}
|
|
@@ -53,8 +108,17 @@ export async function connectRedis(): Promise<boolean> {
|
|
|
53
108
|
|
|
54
109
|
export async function disconnectRedis(): Promise<void> {
|
|
55
110
|
if (redis) {
|
|
56
|
-
|
|
111
|
+
const client = redis;
|
|
57
112
|
redis = null;
|
|
113
|
+
closingOnPurpose = true;
|
|
114
|
+
readyListeners.clear();
|
|
115
|
+
if (client.status === 'ready') {
|
|
116
|
+
await client.quit();
|
|
117
|
+
} else {
|
|
118
|
+
// Not connected (Redis down / still retrying): quit() would be rejected
|
|
119
|
+
// because the offline queue is off. disconnect() stops the retry loop.
|
|
120
|
+
client.disconnect();
|
|
121
|
+
}
|
|
58
122
|
logger.info('[REDIS] Disconnected');
|
|
59
123
|
}
|
|
60
124
|
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { crc32, deflateSync } from 'node:zlib';
|
|
3
|
+
import sharp from 'sharp';
|
|
4
|
+
import { imageOptimizerService, MAX_INPUT_PIXELS } from '../image-optimizer.service.js';
|
|
5
|
+
|
|
6
|
+
// Avatars are public: the output must carry no metadata (GPS, device), and a
|
|
7
|
+
// small file describing a huge picture must be refused before it is decoded.
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A ~70-byte PNG whose header claims width×height. Its pixel data is truncated:
|
|
11
|
+
* enough for the header to be read, which is exactly where the limit must act.
|
|
12
|
+
*/
|
|
13
|
+
function pngHeaderOnly(width: number, height: number): Buffer {
|
|
14
|
+
const chunk = (type: string, data: Buffer): Buffer => {
|
|
15
|
+
const length = Buffer.alloc(4);
|
|
16
|
+
length.writeUInt32BE(data.length);
|
|
17
|
+
const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
|
|
18
|
+
const crc = Buffer.alloc(4);
|
|
19
|
+
crc.writeUInt32BE(crc32(body) >>> 0);
|
|
20
|
+
return Buffer.concat([length, body, crc]);
|
|
21
|
+
};
|
|
22
|
+
const ihdr = Buffer.alloc(13);
|
|
23
|
+
ihdr.writeUInt32BE(width, 0);
|
|
24
|
+
ihdr.writeUInt32BE(height, 4);
|
|
25
|
+
ihdr[8] = 8; // bit depth
|
|
26
|
+
ihdr[9] = 2; // colour type RGB
|
|
27
|
+
return Buffer.concat([
|
|
28
|
+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
29
|
+
chunk('IHDR', ihdr),
|
|
30
|
+
chunk('IDAT', deflateSync(Buffer.alloc(64))),
|
|
31
|
+
chunk('IEND', Buffer.alloc(0)),
|
|
32
|
+
]);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe('imageOptimizerService.optimizeAvatar', () => {
|
|
36
|
+
it('strips EXIF/GPS/XMP and applies the orientation tag to the pixels', async () => {
|
|
37
|
+
const input = await sharp({ create: { width: 64, height: 32, channels: 3, background: '#808080' } })
|
|
38
|
+
.jpeg()
|
|
39
|
+
.withExif({
|
|
40
|
+
IFD0: { Make: 'DummyCam', Model: 'DummyModel' },
|
|
41
|
+
IFD3: { GPSLatitudeRef: 'N', GPSLatitude: '1/1 2/1 3/1', GPSLongitudeRef: 'E', GPSLongitude: '4/1 5/1 6/1' },
|
|
42
|
+
})
|
|
43
|
+
.withMetadata({ orientation: 6 }) // "rotate 90° clockwise" tag, as phones write it
|
|
44
|
+
.toBuffer();
|
|
45
|
+
expect((await sharp(input).metadata()).exif).toBeDefined();
|
|
46
|
+
|
|
47
|
+
const output = await imageOptimizerService.optimizeAvatar(input);
|
|
48
|
+
const meta = await sharp(output).metadata();
|
|
49
|
+
|
|
50
|
+
expect(meta.format).toBe('webp');
|
|
51
|
+
expect(meta.exif).toBeUndefined();
|
|
52
|
+
expect(meta.xmp).toBeUndefined();
|
|
53
|
+
expect(meta.orientation).toBeUndefined();
|
|
54
|
+
// 64×32 landscape + orientation 6 → stored upright as 32×64
|
|
55
|
+
expect(meta.width).toBe(32);
|
|
56
|
+
expect(meta.height).toBe(64);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('refuses an image above the pixel limit without decoding it', async () => {
|
|
60
|
+
const huge = pngHeaderOnly(16000, 16000); // 256 MP claimed, a few dozen bytes
|
|
61
|
+
expect(16000 * 16000).toBeGreaterThan(MAX_INPUT_PIXELS);
|
|
62
|
+
|
|
63
|
+
const started = Date.now();
|
|
64
|
+
await expect(imageOptimizerService.optimizeAvatar(huge)).rejects.toMatchObject({ code: 'IMAGE_TOO_LARGE' });
|
|
65
|
+
expect(Date.now() - started).toBeLessThan(1000);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('refuses formats outside the allowlist even when named like a PNG', async () => {
|
|
69
|
+
const gif = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#ff0000' } }).gif().toBuffer();
|
|
70
|
+
await expect(imageOptimizerService.optimizeAvatar(gif)).rejects.toMatchObject({
|
|
71
|
+
code: 'UNSUPPORTED_IMAGE_FORMAT',
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('accepts a normal photo-sized JPEG', async () => {
|
|
76
|
+
const photo = await sharp({ create: { width: 4000, height: 3000, channels: 3, background: '#336699' } })
|
|
77
|
+
.jpeg()
|
|
78
|
+
.toBuffer();
|
|
79
|
+
const output = await imageOptimizerService.optimizeAvatar(photo);
|
|
80
|
+
const meta = await sharp(output).metadata();
|
|
81
|
+
expect(meta.width).toBe(512);
|
|
82
|
+
expect(meta.height).toBe(384);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
@@ -126,6 +126,17 @@ class FileStorageService {
|
|
|
126
126
|
// Write file to disk (overwrites existing)
|
|
127
127
|
await fs.writeFile(filePath, buffer);
|
|
128
128
|
|
|
129
|
+
// Remove any previous avatar files. The filename comes from the user's
|
|
130
|
+
// name, so after a name change the old file would otherwise stay publicly
|
|
131
|
+
// reachable at its old URL (possibly with metadata from before EXIF
|
|
132
|
+
// stripping). New file is written first, so there is never a moment with
|
|
133
|
+
// no avatar.
|
|
134
|
+
for (const entry of await fs.readdir(avatarDir)) {
|
|
135
|
+
if (entry !== filename) {
|
|
136
|
+
await fs.rm(path.join(avatarDir, entry), { force: true, recursive: true });
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
129
140
|
// Generate public URL
|
|
130
141
|
const url = `/uploads/users/${userId}/avatar/${filename}`;
|
|
131
142
|
|
|
@@ -176,10 +187,13 @@ class FileStorageService {
|
|
|
176
187
|
}
|
|
177
188
|
|
|
178
189
|
/**
|
|
179
|
-
* Deletes all media for a user
|
|
190
|
+
* Deletes all media for a user: the public directory (avatars) AND the
|
|
191
|
+
* private directory (owner-only files).
|
|
180
192
|
*
|
|
181
|
-
* Used by the cleanup job when permanently purging deleted accounts
|
|
182
|
-
*
|
|
193
|
+
* Used by the cleanup job when permanently purging deleted accounts, which
|
|
194
|
+
* promises that nothing of the user remains. It used to delete only the
|
|
195
|
+
* public tier, so private files outlived the account.
|
|
196
|
+
* No-op for a directory that doesn't exist.
|
|
183
197
|
*
|
|
184
198
|
* @param userId - User's unique ID
|
|
185
199
|
*
|
|
@@ -190,15 +204,12 @@ class FileStorageService {
|
|
|
190
204
|
*/
|
|
191
205
|
async deleteUserMedia(userId: string): Promise<void> {
|
|
192
206
|
try {
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
return;
|
|
207
|
+
for (const dir of [this.getUserDir(userId), this.getUserPrivateDir(userId)]) {
|
|
208
|
+
if (await this.directoryExists(dir)) {
|
|
209
|
+
await fs.rm(dir, { recursive: true, force: true });
|
|
210
|
+
}
|
|
198
211
|
}
|
|
199
212
|
|
|
200
|
-
await fs.rm(userDir, { recursive: true, force: true });
|
|
201
|
-
|
|
202
213
|
logger.info({ msg: 'User media deleted successfully', userId });
|
|
203
214
|
} catch (error) {
|
|
204
215
|
logger.error({ err: error, msg: 'Failed to delete user media', userId });
|