create-tigra 3.1.1 → 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/README.md +1 -1
- package/bin/create-tigra.js +6 -5
- 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/.claude/skills/security-audit/SKILL.md +10 -0
- package/template/AGENTS.md +18 -2
- package/template/CLAUDE.md +1 -0
- package/template/client/CLAUDE.md +1 -0
- 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/CLAUDE.md +1 -0
- 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,62 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import type { FastifyReply } from 'fastify';
|
|
3
|
+
import { setAuthCookies, clearAuthCookies } from '../cookies.js';
|
|
4
|
+
|
|
5
|
+
// Production cross-subdomain setup: only the non-secret auth_session indicator
|
|
6
|
+
// may use COOKIE_DOMAIN; the bearer token cookies must stay host-only.
|
|
7
|
+
|
|
8
|
+
vi.mock('@config/env.js', () => ({
|
|
9
|
+
env: {
|
|
10
|
+
NODE_ENV: 'production',
|
|
11
|
+
COOKIE_DOMAIN: '.example.test',
|
|
12
|
+
JWT_ACCESS_EXPIRY: '15m',
|
|
13
|
+
JWT_REFRESH_EXPIRY: '7d',
|
|
14
|
+
},
|
|
15
|
+
}));
|
|
16
|
+
|
|
17
|
+
type CookieOpts = { domain?: string; path?: string; httpOnly?: boolean; secure?: boolean };
|
|
18
|
+
|
|
19
|
+
function fakeReply(): { reply: FastifyReply; set: Map<string, CookieOpts>; cleared: Array<[string, CookieOpts]> } {
|
|
20
|
+
const set = new Map<string, CookieOpts>();
|
|
21
|
+
const cleared: Array<[string, CookieOpts]> = [];
|
|
22
|
+
const reply = {
|
|
23
|
+
setCookie: vi.fn((name: string, _value: string, opts: CookieOpts) => set.set(name, opts)),
|
|
24
|
+
clearCookie: vi.fn((name: string, opts: CookieOpts) => cleared.push([name, opts])),
|
|
25
|
+
} as unknown as FastifyReply;
|
|
26
|
+
return { reply, set, cleared };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe('setAuthCookies', () => {
|
|
30
|
+
it('keeps access and refresh tokens host-only and shares only auth_session', () => {
|
|
31
|
+
const { reply, set } = fakeReply();
|
|
32
|
+
setAuthCookies(reply, 'access', 'refresh');
|
|
33
|
+
|
|
34
|
+
expect(set.get('access_token')?.domain).toBeUndefined();
|
|
35
|
+
expect(set.get('refresh_token')?.domain).toBeUndefined();
|
|
36
|
+
expect(set.get('access_token')?.httpOnly).toBe(true);
|
|
37
|
+
expect(set.get('access_token')?.secure).toBe(true);
|
|
38
|
+
expect(set.get('auth_session')?.domain).toBe('.example.test');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('expires legacy domain-wide token cookies from older versions', () => {
|
|
42
|
+
const { reply, cleared } = fakeReply();
|
|
43
|
+
setAuthCookies(reply, 'access', 'refresh');
|
|
44
|
+
|
|
45
|
+
expect(cleared).toContainEqual(['access_token', expect.objectContaining({ domain: '.example.test', path: '/' })]);
|
|
46
|
+
expect(cleared).toContainEqual([
|
|
47
|
+
'refresh_token',
|
|
48
|
+
expect.objectContaining({ domain: '.example.test', path: '/api/v1/auth' }),
|
|
49
|
+
]);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
describe('clearAuthCookies', () => {
|
|
54
|
+
it('clears both the host-only tokens and any legacy domain-wide copies', () => {
|
|
55
|
+
const { reply, cleared } = fakeReply();
|
|
56
|
+
clearAuthCookies(reply);
|
|
57
|
+
|
|
58
|
+
const tokenClears = cleared.filter(([name]) => name === 'access_token');
|
|
59
|
+
expect(tokenClears.map(([, o]) => o.domain).sort()).toEqual(['.example.test', undefined].sort());
|
|
60
|
+
expect(cleared).toContainEqual(['auth_session', expect.objectContaining({ domain: '.example.test' })]);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { redisRetryDelay } from '../redis.js';
|
|
3
|
+
|
|
4
|
+
// The Redis client must never stop reconnecting: ioredis gives up for good
|
|
5
|
+
// when the retry strategy returns null, which used to leave a process without
|
|
6
|
+
// rate limits, IP blocks and login lockout until it was restarted.
|
|
7
|
+
|
|
8
|
+
describe('redisRetryDelay', () => {
|
|
9
|
+
it('always returns a delay, even after many attempts (never gives up)', () => {
|
|
10
|
+
for (const attempt of [1, 3, 5, 50, 1000, 100000]) {
|
|
11
|
+
const delay = redisRetryDelay(attempt);
|
|
12
|
+
expect(typeof delay).toBe('number');
|
|
13
|
+
expect(delay).toBeGreaterThan(0);
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('backs off and caps the wait at 5 seconds', () => {
|
|
18
|
+
expect(redisRetryDelay(1)).toBe(200);
|
|
19
|
+
expect(redisRetryDelay(2)).toBe(400);
|
|
20
|
+
expect(redisRetryDelay(25)).toBe(5000);
|
|
21
|
+
expect(redisRetryDelay(10000)).toBe(5000);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import type { Event } from '@sentry/node';
|
|
3
|
+
import { scrubSentryEvent } from '../observability/sentry.js';
|
|
4
|
+
|
|
5
|
+
// Error events must never carry passwords, tokens or cookies to Sentry.
|
|
6
|
+
|
|
7
|
+
describe('scrubSentryEvent', () => {
|
|
8
|
+
it('removes request body, cookies, auth headers and query strings', () => {
|
|
9
|
+
const event: Event = {
|
|
10
|
+
request: {
|
|
11
|
+
url: 'https://api.example.test/api/v1/auth/reset-password?token=secret-reset-token',
|
|
12
|
+
method: 'POST',
|
|
13
|
+
data: '{"email":"a@example.test","password":"Plaintext-Passw0rd"}',
|
|
14
|
+
cookies: { access_token: 'jwt-value', refresh_token: 'refresh-value' },
|
|
15
|
+
query_string: 'token=secret-reset-token',
|
|
16
|
+
headers: {
|
|
17
|
+
Cookie: 'access_token=jwt-value; refresh_token=refresh-value',
|
|
18
|
+
authorization: 'Bearer jwt-value',
|
|
19
|
+
'user-agent': 'vitest',
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
breadcrumbs: [
|
|
23
|
+
{ category: 'http', data: { url: 'https://x.test/verify-account?token=abc', 'http.query': 'token=abc' } },
|
|
24
|
+
],
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const scrubbed = scrubSentryEvent(event);
|
|
28
|
+
const serialized = JSON.stringify(scrubbed);
|
|
29
|
+
|
|
30
|
+
expect(serialized).not.toContain('Plaintext-Passw0rd');
|
|
31
|
+
expect(serialized).not.toContain('jwt-value');
|
|
32
|
+
expect(serialized).not.toContain('refresh-value');
|
|
33
|
+
expect(serialized).not.toContain('secret-reset-token');
|
|
34
|
+
expect(serialized).not.toContain('token=abc');
|
|
35
|
+
// Useful, non-secret context survives
|
|
36
|
+
expect(scrubbed.request?.method).toBe('POST');
|
|
37
|
+
expect(scrubbed.request?.url).toBe('https://api.example.test/api/v1/auth/reset-password');
|
|
38
|
+
expect(scrubbed.request?.headers?.['user-agent']).toBe('vitest');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('strips tokens from the Referer header, trace data, span attributes and the transaction name', () => {
|
|
42
|
+
// The browser SDK copies the page URL and the Referer into request headers
|
|
43
|
+
// and span/trace attributes; reset/verify pages carry ?token=… there.
|
|
44
|
+
const event: Event = {
|
|
45
|
+
transaction: '/verify-account?token=txn-secret',
|
|
46
|
+
request: { headers: { Referer: 'https://app.example.test/reset-password?token=referer-secret' } },
|
|
47
|
+
contexts: {
|
|
48
|
+
trace: {
|
|
49
|
+
trace_id: 't',
|
|
50
|
+
span_id: 's',
|
|
51
|
+
data: {
|
|
52
|
+
'url.full': 'https://app.example.test/reset-password?token=trace-secret',
|
|
53
|
+
'http.request.header.referer': 'https://app.example.test/verify-account?token=trace-ref-secret',
|
|
54
|
+
'http.query': 'token=trace-query-secret',
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
spans: [
|
|
59
|
+
{
|
|
60
|
+
span_id: 'x',
|
|
61
|
+
trace_id: 't',
|
|
62
|
+
start_timestamp: 0,
|
|
63
|
+
data: { 'http.request.header.referer': 'https://app.example.test/x?token=span-secret' },
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const serialized = JSON.stringify(scrubSentryEvent(event));
|
|
69
|
+
|
|
70
|
+
for (const secret of ['txn-secret', 'referer-secret', 'trace-secret', 'trace-ref-secret', 'trace-query-secret', 'span-secret']) {
|
|
71
|
+
expect(serialized).not.toContain(secret);
|
|
72
|
+
}
|
|
73
|
+
expect(serialized).toContain('https://app.example.test/reset-password');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('leaves an event without request data untouched', () => {
|
|
77
|
+
const event: Event = { message: 'boom' };
|
|
78
|
+
expect(scrubSentryEvent(event)).toEqual({ message: 'boom' });
|
|
79
|
+
});
|
|
80
|
+
});
|
|
@@ -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
|
}
|