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
|
@@ -229,11 +229,34 @@ function patchRateLimitConfig(project, targetDir) {
|
|
|
229
229
|
sourceFile.saveSync();
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
+
/**
|
|
233
|
+
* Replace one exact text anchor, failing loudly when it is missing.
|
|
234
|
+
*
|
|
235
|
+
* Text anchors used to skip silently, which hid a real bug: the login resend
|
|
236
|
+
* anchor never matched the template, yet the CLI reported the file as patched.
|
|
237
|
+
* Now a missing anchor stops the patch with a clear error. `alreadyPatchedMarker`
|
|
238
|
+
* makes re-running the patcher a no-op. Anchors are written with "\n"; they are
|
|
239
|
+
* matched against CRLF files too (Windows checkouts with core.autocrlf).
|
|
240
|
+
*/
|
|
241
|
+
function replaceAnchor(content, { anchor, replacement, alreadyPatchedMarker, label, file }) {
|
|
242
|
+
if (content.includes(alreadyPatchedMarker)) return content;
|
|
243
|
+
const eol = content.includes('\r\n') ? '\r\n' : '\n';
|
|
244
|
+
const anchorText = anchor.split('\n').join(eol);
|
|
245
|
+
if (!content.includes(anchorText)) {
|
|
246
|
+
throw new Error(
|
|
247
|
+
`Could not find the ${label} in ${file} — file may have been modified. ` +
|
|
248
|
+
'Apply the email-verification change by hand or restore the template code.',
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
return content.replace(anchorText, replacement.split('\n').join(eol));
|
|
252
|
+
}
|
|
253
|
+
|
|
232
254
|
/**
|
|
233
255
|
* Patch 4: auth.service.ts
|
|
234
256
|
* - Export sanitizeUser function, SanitizedUser interface, AuthResult interface
|
|
235
257
|
* so verification.service.ts can import them
|
|
236
|
-
* - Add import for sendVerification and call it during register (auto-send on
|
|
258
|
+
* - Add import for sendVerification and call it during register (auto-send on
|
|
259
|
+
* signup) and on a correct-password login of an unverified, non-banned account
|
|
237
260
|
*/
|
|
238
261
|
function patchAuthService(project, targetDir) {
|
|
239
262
|
const filePath = path.join(targetDir, 'server', 'src', 'modules', 'auth', 'auth.service.ts');
|
|
@@ -292,18 +315,39 @@ function patchAuthService(project, targetDir) {
|
|
|
292
315
|
let patched = content;
|
|
293
316
|
|
|
294
317
|
// Patch 1: Auto-send verification email on registration
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
}
|
|
318
|
+
patched = replaceAnchor(patched, {
|
|
319
|
+
file: 'auth.service.ts',
|
|
320
|
+
label: 'register verification branch',
|
|
321
|
+
alreadyPatchedMarker: 'sendVerification(input.email)',
|
|
322
|
+
anchor: ' if (requiresVerification) {\n return {\n user: sanitizeUser(user),\n requiresVerification: true,\n };\n }',
|
|
323
|
+
replacement:
|
|
324
|
+
' if (requiresVerification) {\n' +
|
|
325
|
+
" // Auto-send verification email on registration (best-effort, don't block registration)\n" +
|
|
326
|
+
' sendVerification(input.email).catch(() => {});\n\n' +
|
|
327
|
+
' return {\n user: sanitizeUser(user),\n requiresVerification: true,\n };\n }',
|
|
328
|
+
});
|
|
300
329
|
|
|
301
|
-
// Patch 2:
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
330
|
+
// Patch 2: Re-send a fresh link when an unverified user logs in with the
|
|
331
|
+
// correct password. It runs after the password check, so an anonymous caller
|
|
332
|
+
// cannot trigger emails, and never for a banned account (verification cannot
|
|
333
|
+
// lift a ban). assertAccountCanSignIn then answers 403 EMAIL_NOT_VERIFIED.
|
|
334
|
+
patched = replaceAnchor(patched, {
|
|
335
|
+
file: 'auth.service.ts',
|
|
336
|
+
label: 'login account-state check',
|
|
337
|
+
alreadyPatchedMarker: 'sendVerification(user.email)',
|
|
338
|
+
anchor:
|
|
339
|
+
' // Reveal account state only now that the password is proven, so an anonymous\n' +
|
|
340
|
+
' // caller cannot learn whether an email is banned or unverified.\n' +
|
|
341
|
+
' assertAccountCanSignIn(user);',
|
|
342
|
+
replacement:
|
|
343
|
+
' // Reveal account state only now that the password is proven, so an anonymous\n' +
|
|
344
|
+
' // caller cannot learn whether an email is banned or unverified.\n' +
|
|
345
|
+
' // Email-verification module: re-send a fresh link to an unverified (not banned) account.\n' +
|
|
346
|
+
' if (user.isActive && env.REQUIRE_USER_VERIFICATION && !user.emailVerifiedAt) {\n' +
|
|
347
|
+
' sendVerification(user.email).catch(() => {});\n' +
|
|
348
|
+
' }\n' +
|
|
349
|
+
' assertAccountCanSignIn(user);',
|
|
350
|
+
});
|
|
307
351
|
|
|
308
352
|
if (patched !== content) {
|
|
309
353
|
fs.writeFileSync(filePath, patched, 'utf-8');
|
|
@@ -312,26 +356,35 @@ function patchAuthService(project, targetDir) {
|
|
|
312
356
|
|
|
313
357
|
/**
|
|
314
358
|
* Patch 5: auth.repo.ts
|
|
315
|
-
* - Add
|
|
359
|
+
* - Add markEmailVerified function at end of file
|
|
360
|
+
*
|
|
361
|
+
* It sets emailVerifiedAt only for an active, not-yet-verified, non-deleted
|
|
362
|
+
* account and never touches isActive (the admin ban switch). The conditional
|
|
363
|
+
* write means a ban that lands mid-verification still wins. Returns whether a
|
|
364
|
+
* row was updated.
|
|
316
365
|
*/
|
|
317
366
|
function patchAuthRepo(project, targetDir) {
|
|
318
367
|
const filePath = path.join(targetDir, 'server', 'src', 'modules', 'auth', 'auth.repo.ts');
|
|
319
368
|
const sourceFile = project.addSourceFileAtPath(filePath);
|
|
320
369
|
|
|
321
370
|
// Check if already patched
|
|
322
|
-
const existing = sourceFile.getFunction('
|
|
371
|
+
const existing = sourceFile.getFunction('markEmailVerified');
|
|
323
372
|
if (existing) return;
|
|
324
373
|
|
|
325
374
|
sourceFile.addFunction({
|
|
326
|
-
name: '
|
|
375
|
+
name: 'markEmailVerified',
|
|
327
376
|
isExported: true,
|
|
328
377
|
isAsync: true,
|
|
329
|
-
parameters: [
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
378
|
+
parameters: [
|
|
379
|
+
{ name: 'userId', type: 'string' },
|
|
380
|
+
{ name: 'verifiedAt', type: 'Date' },
|
|
381
|
+
],
|
|
382
|
+
returnType: 'Promise<boolean>',
|
|
383
|
+
statements: `const result = await prisma.user.updateMany({
|
|
384
|
+
where: { id: userId, isActive: true, emailVerifiedAt: null, deletedAt: null },
|
|
385
|
+
data: { emailVerifiedAt: verifiedAt },
|
|
386
|
+
});
|
|
387
|
+
return result.count === 1;`,
|
|
335
388
|
});
|
|
336
389
|
|
|
337
390
|
sourceFile.saveSync();
|
|
@@ -444,31 +497,32 @@ function patchErrorCodes(project, targetDir) {
|
|
|
444
497
|
|
|
445
498
|
/**
|
|
446
499
|
* Patch 8: useAuth.ts (client)
|
|
447
|
-
* - Redirect to /verify-account when login fails with
|
|
448
|
-
* (the server auto-resends the verification email on this error)
|
|
500
|
+
* - Redirect to /verify-account when login fails with EMAIL_NOT_VERIFIED
|
|
501
|
+
* (the server auto-resends the verification email on this error).
|
|
502
|
+
* Banned accounts (ACCOUNT_DEACTIVATED) are deliberately NOT sent there:
|
|
503
|
+
* verifying an email cannot lift a ban.
|
|
449
504
|
*/
|
|
450
505
|
function patchUseAuthHook(targetDir) {
|
|
451
506
|
const filePath = path.join(targetDir, 'client', 'src', 'features', 'auth', 'hooks', 'useAuth.ts');
|
|
452
|
-
if (!fs.pathExistsSync(filePath))
|
|
507
|
+
if (!fs.pathExistsSync(filePath)) {
|
|
508
|
+
throw new Error('Could not find client/src/features/auth/hooks/useAuth.ts — file may have been moved');
|
|
509
|
+
}
|
|
453
510
|
|
|
454
511
|
const content = fs.readFileSync(filePath, 'utf-8');
|
|
455
512
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
// Replace the toast message and add router.push right after it
|
|
466
|
-
const patched = content.replace(
|
|
467
|
-
anchorText,
|
|
468
|
-
"toast.error('Your account is not yet activated. Check your email for a verification link.');\n router.push(ROUTES.VERIFY_ACCOUNT);",
|
|
469
|
-
);
|
|
513
|
+
const patched = replaceAnchor(content, {
|
|
514
|
+
file: 'useAuth.ts',
|
|
515
|
+
label: 'EMAIL_NOT_VERIFIED login error toast',
|
|
516
|
+
alreadyPatchedMarker: 'We sent you a new verification link',
|
|
517
|
+
anchor: "toast.error('Please verify your email address before signing in.');",
|
|
518
|
+
replacement:
|
|
519
|
+
"toast.error('Please verify your email address. We sent you a new verification link.');\n" +
|
|
520
|
+
' router.push(ROUTES.VERIFY_ACCOUNT);',
|
|
521
|
+
});
|
|
470
522
|
|
|
471
|
-
|
|
523
|
+
if (patched !== content) {
|
|
524
|
+
fs.writeFileSync(filePath, patched, 'utf-8');
|
|
525
|
+
}
|
|
472
526
|
}
|
|
473
527
|
|
|
474
528
|
// ─── Postman Patch ──────────────────────────────────────────────
|
|
@@ -4,8 +4,10 @@ import { getRedis } from '@libs/redis.js';
|
|
|
4
4
|
import { sendEmail } from '@libs/email.js';
|
|
5
5
|
import { logger } from '@libs/logger.js';
|
|
6
6
|
import { env } from '@config/env.js';
|
|
7
|
+
import { ACCOUNT_DEACTIVATED } from '@libs/account-status.js';
|
|
7
8
|
import {
|
|
8
9
|
BadRequestError,
|
|
10
|
+
ForbiddenError,
|
|
9
11
|
NotFoundError,
|
|
10
12
|
} from '@shared/errors/errors.js';
|
|
11
13
|
import * as authRepo from './auth.repo.js';
|
|
@@ -21,7 +23,10 @@ const VERIFICATION_USER_PREFIX = 'verify-user:';
|
|
|
21
23
|
/**
|
|
22
24
|
* Send a verification email to a user.
|
|
23
25
|
* Public endpoint — accepts email, silent return if user not found (prevents enumeration).
|
|
24
|
-
* Also called internally by the register
|
|
26
|
+
* Also called internally by the register and login flows for auto-sending.
|
|
27
|
+
*
|
|
28
|
+
* Verification proves email ownership and nothing else: it sets
|
|
29
|
+
* `emailVerifiedAt` and never touches `isActive` (the admin ban switch).
|
|
25
30
|
*/
|
|
26
31
|
export async function sendVerification(email: string): Promise<void> {
|
|
27
32
|
const user = await authRepo.findUserByEmail(email);
|
|
@@ -29,8 +34,11 @@ export async function sendVerification(email: string): Promise<void> {
|
|
|
29
34
|
// Silent return if user not found — prevents email enumeration (same pattern as forgotPassword)
|
|
30
35
|
if (!user) return;
|
|
31
36
|
|
|
32
|
-
//
|
|
33
|
-
|
|
37
|
+
// No token for a banned account: a verify link must never lift an admin ban
|
|
38
|
+
// (that is exactly how a banned user used to re-activate themselves). No
|
|
39
|
+
// token either when the email is already verified. Both stay silent so the
|
|
40
|
+
// response does not reveal the account's status.
|
|
41
|
+
if (!user.isActive || user.emailVerifiedAt) return;
|
|
34
42
|
|
|
35
43
|
const redis = getRedis();
|
|
36
44
|
|
|
@@ -107,7 +115,8 @@ export async function verifyAccount(
|
|
|
107
115
|
const redis = getRedis();
|
|
108
116
|
|
|
109
117
|
// Atomic get-and-delete to prevent token reuse via concurrent requests
|
|
110
|
-
|
|
118
|
+
// ioredis exposes GETDEL as getdel (all lowercase); getDel does not exist.
|
|
119
|
+
const userId = await redis.getdel(`${VERIFICATION_PREFIX}${token}`);
|
|
111
120
|
if (!userId) {
|
|
112
121
|
throw new BadRequestError('Invalid or expired verification token', 'INVALID_VERIFICATION_TOKEN');
|
|
113
122
|
}
|
|
@@ -117,12 +126,32 @@ export async function verifyAccount(
|
|
|
117
126
|
throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
118
127
|
}
|
|
119
128
|
|
|
120
|
-
//
|
|
121
|
-
await authRepo.activateUser(userId);
|
|
122
|
-
|
|
123
|
-
// Clean up the reverse-lookup key
|
|
129
|
+
// Clean up the reverse-lookup key (the token itself was consumed above)
|
|
124
130
|
await redis.del(`${VERIFICATION_USER_PREFIX}${userId}`);
|
|
125
131
|
|
|
132
|
+
// A token issued before a ban must not lift the ban or open a session.
|
|
133
|
+
if (!user.isActive) {
|
|
134
|
+
throw new ForbiddenError(
|
|
135
|
+
'This account has been deactivated. Contact support if you think this is a mistake.',
|
|
136
|
+
ACCOUNT_DEACTIVATED,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Conditional write: only an active, not-yet-verified account is marked. If a
|
|
141
|
+
// ban lands between the read above and this write, the ban wins.
|
|
142
|
+
const verifiedAt = new Date();
|
|
143
|
+
const marked = await authRepo.markEmailVerified(userId, verifiedAt);
|
|
144
|
+
if (!marked) {
|
|
145
|
+
const current = await authRepo.findUserById(userId);
|
|
146
|
+
if (!current || !current.isActive) {
|
|
147
|
+
throw new ForbiddenError(
|
|
148
|
+
'This account has been deactivated. Contact support if you think this is a mistake.',
|
|
149
|
+
ACCOUNT_DEACTIVATED,
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
throw new BadRequestError('This email address is already verified', 'ALREADY_VERIFIED');
|
|
153
|
+
}
|
|
154
|
+
|
|
126
155
|
// Generate tokens and create session (same pattern as login)
|
|
127
156
|
const accessToken = signAccessToken({
|
|
128
157
|
userId: user.id,
|
|
@@ -183,7 +212,7 @@ export async function verifyAccount(
|
|
|
183
212
|
}
|
|
184
213
|
|
|
185
214
|
return {
|
|
186
|
-
user: sanitizeUser({ ...user,
|
|
215
|
+
user: sanitizeUser({ ...user, emailVerifiedAt: verifiedAt }),
|
|
187
216
|
accessToken,
|
|
188
217
|
refreshToken,
|
|
189
218
|
};
|
package/package.json
CHANGED
|
@@ -57,8 +57,10 @@ export const AuthInitializer = ({ children }: AuthInitializerProps): React.React
|
|
|
57
57
|
|
|
58
58
|
const status = (error as HttpLikeError)?.response?.status;
|
|
59
59
|
if (status === 401 || status === 403) {
|
|
60
|
-
if (isErrorCode(error, ERROR_CODES.
|
|
61
|
-
toast.error('
|
|
60
|
+
if (isErrorCode(error, ERROR_CODES.ACCOUNT_DEACTIVATED)) {
|
|
61
|
+
toast.error('This account has been deactivated. Contact support if you think this is a mistake.');
|
|
62
|
+
} else if (isErrorCode(error, ERROR_CODES.EMAIL_NOT_VERIFIED)) {
|
|
63
|
+
toast.error('Please verify your email address before signing in.');
|
|
62
64
|
}
|
|
63
65
|
router.push(ROUTES.LOGIN);
|
|
64
66
|
}
|
|
@@ -16,6 +16,7 @@ import { AppLink } from '@/components/common/AppLink';
|
|
|
16
16
|
import { useAuth } from '../hooks/useAuth';
|
|
17
17
|
import { ROUTES } from '@/lib/constants/routes';
|
|
18
18
|
import { cn } from '@/lib/utils';
|
|
19
|
+
import { getSafeRedirectPath } from '@/lib/utils/security';
|
|
19
20
|
|
|
20
21
|
const loginSchema = z.object({
|
|
21
22
|
email: z.string().min(1, 'Email is required').email('Invalid email address'),
|
|
@@ -27,8 +28,10 @@ type LoginFormData = z.infer<typeof loginSchema>;
|
|
|
27
28
|
const LoginFormInner = (): React.ReactElement => {
|
|
28
29
|
const { login, isLoggingIn } = useAuth();
|
|
29
30
|
const searchParams = useSearchParams();
|
|
30
|
-
|
|
31
|
-
|
|
31
|
+
// `from` is attacker-controllable (anyone can send a /login?from=… link), so
|
|
32
|
+
// only a same-site path is accepted — see getSafeRedirectPath for why a
|
|
33
|
+
// simple prefix check let `/\evil.com` through.
|
|
34
|
+
const redirectTo = getSafeRedirectPath(searchParams.get('from'));
|
|
32
35
|
|
|
33
36
|
const {
|
|
34
37
|
register,
|
|
@@ -9,6 +9,7 @@ import { useAppDispatch, useAppSelector } from '@/store/hooks';
|
|
|
9
9
|
import { useAppRouter } from '@/hooks/useAppRouter';
|
|
10
10
|
import { getErrorMessage, isErrorCode, ERROR_CODES } from '@/lib/utils/error';
|
|
11
11
|
import { ROUTES } from '@/lib/constants/routes';
|
|
12
|
+
import { getSafeRedirectPath } from '@/lib/utils/security';
|
|
12
13
|
import { authService } from '../services/auth.service';
|
|
13
14
|
import { setUser, setLoggingOut, logout as logoutAction } from '../store/authSlice';
|
|
14
15
|
|
|
@@ -42,8 +43,12 @@ export const useAuth = (): UseAuthReturn => {
|
|
|
42
43
|
router.push(pendingRedirectRef.current);
|
|
43
44
|
},
|
|
44
45
|
onError: (error) => {
|
|
45
|
-
if (isErrorCode(error, ERROR_CODES.
|
|
46
|
-
toast.error('
|
|
46
|
+
if (isErrorCode(error, ERROR_CODES.ACCOUNT_DEACTIVATED)) {
|
|
47
|
+
toast.error('This account has been deactivated. Contact support if you think this is a mistake.');
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (isErrorCode(error, ERROR_CODES.EMAIL_NOT_VERIFIED)) {
|
|
51
|
+
toast.error('Please verify your email address before signing in.');
|
|
47
52
|
return;
|
|
48
53
|
}
|
|
49
54
|
toast.error(getErrorMessage(error));
|
|
@@ -53,8 +58,10 @@ export const useAuth = (): UseAuthReturn => {
|
|
|
53
58
|
const registerMutation = useMutation({
|
|
54
59
|
mutationFn: (data: IRegisterRequest) => authService.register(data),
|
|
55
60
|
onSuccess: (data) => {
|
|
56
|
-
|
|
57
|
-
|
|
61
|
+
// No session is issued until the email is verified (server returns the
|
|
62
|
+
// user with emailVerifiedAt = null when verification is required).
|
|
63
|
+
if (!data.user.emailVerifiedAt) {
|
|
64
|
+
toast.success('Account created! Please verify your email address to continue.');
|
|
58
65
|
router.push(ROUTES.VERIFY_ACCOUNT);
|
|
59
66
|
return;
|
|
60
67
|
}
|
|
@@ -86,8 +93,11 @@ export const useAuth = (): UseAuthReturn => {
|
|
|
86
93
|
isAuthenticated,
|
|
87
94
|
isInitializing,
|
|
88
95
|
login: (data: ILoginRequest, redirectTo?: string) => {
|
|
89
|
-
|
|
90
|
-
|
|
96
|
+
// Validate again at the sink: whatever a caller passes, router.push after
|
|
97
|
+
// login only ever receives a same-site path.
|
|
98
|
+
const safeRedirect = getSafeRedirectPath(redirectTo);
|
|
99
|
+
if (safeRedirect) {
|
|
100
|
+
pendingRedirectRef.current = safeRedirect;
|
|
91
101
|
}
|
|
92
102
|
loginMutation.mutate(data);
|
|
93
103
|
},
|
|
@@ -4,7 +4,10 @@ export interface IUser {
|
|
|
4
4
|
firstName: string;
|
|
5
5
|
lastName: string;
|
|
6
6
|
role: UserRole;
|
|
7
|
+
/** Admin ban switch: false = deactivated by an admin. */
|
|
7
8
|
isActive: boolean;
|
|
9
|
+
/** ISO timestamp of email verification; null while unverified. */
|
|
10
|
+
emailVerifiedAt: string | null;
|
|
8
11
|
avatarUrl: string | null;
|
|
9
12
|
createdAt: string;
|
|
10
13
|
updatedAt: string;
|
|
@@ -15,12 +15,20 @@ let sentryPromise: Promise<SentryNext> | null = null;
|
|
|
15
15
|
function loadSentry(): Promise<SentryNext | null> {
|
|
16
16
|
if (!sentryEnabled || !dsn) return Promise.resolve(null);
|
|
17
17
|
|
|
18
|
-
sentryPromise ??=
|
|
18
|
+
sentryPromise ??= Promise.all([
|
|
19
|
+
import('@sentry/nextjs'),
|
|
20
|
+
import('./lib/observability/sentry-scrub'),
|
|
21
|
+
]).then(([Sentry, { scrubSentryEvent }]) => {
|
|
19
22
|
Sentry.init({
|
|
20
23
|
dsn,
|
|
21
24
|
tracesSampleRate: process.env.NEXT_PUBLIC_SENTRY_TRACES_SAMPLE_RATE
|
|
22
25
|
? Number(process.env.NEXT_PUBLIC_SENTRY_TRACES_SAMPLE_RATE)
|
|
23
26
|
: 0.1,
|
|
27
|
+
sendDefaultPii: false,
|
|
28
|
+
// Page URLs like /reset-password?token=… and /verify-account?token=…
|
|
29
|
+
// carry credentials: strip query strings and cookies from every event.
|
|
30
|
+
beforeSend: (event) => scrubSentryEvent(event),
|
|
31
|
+
beforeSendTransaction: (event) => scrubSentryEvent(event),
|
|
24
32
|
});
|
|
25
33
|
|
|
26
34
|
return Sentry;
|
|
@@ -27,10 +27,16 @@ export async function register(): Promise<void> {
|
|
|
27
27
|
if (!Sentry || !dsn) return;
|
|
28
28
|
|
|
29
29
|
if (process.env.NEXT_RUNTIME === 'nodejs' || process.env.NEXT_RUNTIME === 'edge') {
|
|
30
|
+
const { scrubSentryEvent } = await import('./lib/observability/sentry-scrub');
|
|
30
31
|
Sentry.init({
|
|
31
32
|
dsn,
|
|
32
33
|
tracesSampleRate,
|
|
33
34
|
environment: process.env.SENTRY_ENVIRONMENT ?? process.env.NODE_ENV,
|
|
35
|
+
sendDefaultPii: false,
|
|
36
|
+
// captureRequestError attaches request headers (incl. Cookie): strip
|
|
37
|
+
// cookies, auth headers and token query strings before anything is sent.
|
|
38
|
+
beforeSend: (event) => scrubSentryEvent(event),
|
|
39
|
+
beforeSendTransaction: (event) => scrubSentryEvent(event),
|
|
34
40
|
});
|
|
35
41
|
}
|
|
36
42
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Privacy filter for Sentry events sent from the Next.js app (browser and the
|
|
3
|
+
* Node/Edge server runtime). Mirrors the API server's scrubber
|
|
4
|
+
* (server/src/libs/observability/sentry.ts) — keep the two in step.
|
|
5
|
+
*
|
|
6
|
+
* Why it exists: Next's `captureRequestError` attaches the incoming request's
|
|
7
|
+
* headers (including the Cookie header), and the browser SDK attaches the page
|
|
8
|
+
* URL and the Referer, both as request headers and as span/trace attributes.
|
|
9
|
+
* Page URLs such as /reset-password?token=… and /verify-account?token=… carry
|
|
10
|
+
* credentials, so every URL-like value loses its query string and fragment,
|
|
11
|
+
* and cookie/auth headers are dropped, before anything is sent.
|
|
12
|
+
*
|
|
13
|
+
* Kept dependency-free (type-only import) so it never pulls @sentry/nextjs into
|
|
14
|
+
* a bundle by itself.
|
|
15
|
+
*/
|
|
16
|
+
import type { Event } from '@sentry/nextjs';
|
|
17
|
+
|
|
18
|
+
const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key']);
|
|
19
|
+
const URL_HEADERS = new Set(['referer', 'referrer']);
|
|
20
|
+
|
|
21
|
+
/** Drop the query string and fragment: tokens travel there. */
|
|
22
|
+
function withoutQuery(url: string): string {
|
|
23
|
+
const cut = url.search(/[?#]/);
|
|
24
|
+
return cut === -1 ? url : url.slice(0, cut);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Clean a free-form attribute bag (breadcrumb data, span data, trace data):
|
|
29
|
+
* strip queries from anything URL-like, drop query/cookie/auth attributes.
|
|
30
|
+
*/
|
|
31
|
+
function scrubData(data: Record<string, unknown> | undefined): void {
|
|
32
|
+
if (!data) return;
|
|
33
|
+
for (const key of Object.keys(data)) {
|
|
34
|
+
const lower = key.toLowerCase();
|
|
35
|
+
if (lower.includes('query') || lower.includes('cookie') || lower.includes('authorization')) {
|
|
36
|
+
delete data[key];
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const value = data[key];
|
|
40
|
+
if (
|
|
41
|
+
typeof value === 'string' &&
|
|
42
|
+
(lower.includes('url') || lower.includes('referer') || lower.includes('target') || lower === 'from' || lower === 'to')
|
|
43
|
+
) {
|
|
44
|
+
data[key] = withoutQuery(value);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function scrubSentryEvent<T extends Event>(event: T): T {
|
|
50
|
+
const request = event.request;
|
|
51
|
+
if (request) {
|
|
52
|
+
delete request.data;
|
|
53
|
+
delete request.cookies;
|
|
54
|
+
delete request.query_string;
|
|
55
|
+
if (request.url) request.url = withoutQuery(request.url);
|
|
56
|
+
if (request.headers) {
|
|
57
|
+
for (const name of Object.keys(request.headers)) {
|
|
58
|
+
const lower = name.toLowerCase();
|
|
59
|
+
if (SECRET_HEADERS.has(lower)) delete request.headers[name];
|
|
60
|
+
else if (URL_HEADERS.has(lower)) request.headers[name] = withoutQuery(request.headers[name]);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (event.transaction) event.transaction = withoutQuery(event.transaction);
|
|
66
|
+
for (const crumb of event.breadcrumbs ?? []) scrubData(crumb.data as Record<string, unknown> | undefined);
|
|
67
|
+
for (const span of event.spans ?? []) scrubData(span.data as Record<string, unknown> | undefined);
|
|
68
|
+
scrubData(event.contexts?.trace?.data as Record<string, unknown> | undefined);
|
|
69
|
+
|
|
70
|
+
return event;
|
|
71
|
+
}
|
|
@@ -31,6 +31,10 @@ export const isErrorCode = (error: unknown, code: string): boolean => {
|
|
|
31
31
|
return getErrorCode(error) === code;
|
|
32
32
|
};
|
|
33
33
|
|
|
34
|
+
// Account-state codes from the server (src/libs/account-status.ts). They are
|
|
35
|
+
// separate on purpose: a deactivated (banned) account must never be steered to
|
|
36
|
+
// email verification, because verifying cannot lift a ban.
|
|
34
37
|
export const ERROR_CODES = {
|
|
35
|
-
|
|
38
|
+
ACCOUNT_DEACTIVATED: 'ACCOUNT_DEACTIVATED',
|
|
39
|
+
EMAIL_NOT_VERIFIED: 'EMAIL_NOT_VERIFIED',
|
|
36
40
|
} as const;
|
|
@@ -7,6 +7,43 @@ export const isSafeUrl = (url: string): boolean => {
|
|
|
7
7
|
}
|
|
8
8
|
};
|
|
9
9
|
|
|
10
|
+
// Placeholder origin used only to parse relative paths. It never appears in
|
|
11
|
+
// output and `.invalid` can never resolve, so nothing here can point at it.
|
|
12
|
+
const REDIRECT_PARSE_BASE = 'https://redirect-check.invalid';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Turn an untrusted "where to go next" value (e.g. `?from=` on /login) into a
|
|
16
|
+
* same-site path, or undefined when it isn't one.
|
|
17
|
+
*
|
|
18
|
+
* A prefix check like `startsWith('/') && !startsWith('//')` is NOT enough:
|
|
19
|
+
* browsers treat `\` like `/` and silently drop tabs and newlines, so
|
|
20
|
+
* `/\evil.com` and `/<TAB>/evil.com` both become `//evil.com` — another site.
|
|
21
|
+
* The value is therefore parsed exactly like the browser will, and accepted
|
|
22
|
+
* only if it stays on our origin; we then return just path + query + hash.
|
|
23
|
+
*/
|
|
24
|
+
export const getSafeRedirectPath = (value: string | null | undefined): string | undefined => {
|
|
25
|
+
if (!value || !value.startsWith('/') || value.startsWith('//')) return undefined;
|
|
26
|
+
// Backslashes, control characters and whitespace have no place in an
|
|
27
|
+
// internal path and are exactly what the bypasses rely on.
|
|
28
|
+
if (/[\\\s\u0000-\u001f\u007f]/.test(value)) return undefined;
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
const url = new URL(value, REDIRECT_PARSE_BASE);
|
|
32
|
+
if (url.origin !== REDIRECT_PARSE_BASE) return undefined;
|
|
33
|
+
const path = `${url.pathname}${url.search}${url.hash}`;
|
|
34
|
+
// Check the RESULT, not only the input: dot segments normalize away, so
|
|
35
|
+
// '/..//evil.com' or '/%2e%2e//evil.com' come out as '//evil.com', which
|
|
36
|
+
// the router would treat as another site. The path we return must itself
|
|
37
|
+
// resolve back to our origin.
|
|
38
|
+
if (path.startsWith('//') || new URL(path, REDIRECT_PARSE_BASE).origin !== REDIRECT_PARSE_BASE) {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
return path;
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
10
47
|
export const sanitizeString = (input: string): string => {
|
|
11
48
|
return input
|
|
12
49
|
.trim()
|
|
@@ -184,17 +184,18 @@ JWT_REFRESH_EXPIRY="7d"
|
|
|
184
184
|
|
|
185
185
|
# Cookie signing secret (separate from JWT for defense-in-depth)
|
|
186
186
|
# Optional: defaults to JWT_SECRET if not set
|
|
187
|
-
# For production: generate a separate secret: openssl rand -
|
|
187
|
+
# For production: generate a separate secret: openssl rand -hex 48
|
|
188
188
|
# COOLIFY: Runtime only. Do NOT check "Available at Buildtime" — this is a secret!
|
|
189
|
-
# COOKIE_SECRET="
|
|
189
|
+
# COOKIE_SECRET="CHANGE_ME_generate_with_openssl_rand_hex_48"
|
|
190
190
|
|
|
191
191
|
# Cookie domain for cross-origin deployments
|
|
192
192
|
# REQUIRED when client and API are on different subdomains:
|
|
193
193
|
# Client: https://app.example.com | API: https://api.example.com
|
|
194
194
|
# → Set COOKIE_DOMAIN=".example.com" (note the leading dot)
|
|
195
195
|
# NOT needed when client and API share the same hostname (local dev, same-origin prod)
|
|
196
|
-
#
|
|
197
|
-
#
|
|
196
|
+
# It scopes ONLY the non-secret auth_session indicator, so the client's Next.js
|
|
197
|
+
# middleware can see that a session exists. The access/refresh token cookies stay
|
|
198
|
+
# host-only on the API (never shared with other subdomains).
|
|
198
199
|
# COOKIE_DOMAIN=".example.com"
|
|
199
200
|
|
|
200
201
|
# ===================================================================
|
|
@@ -142,18 +142,21 @@ MAX_FILE_SIZE_MB=10
|
|
|
142
142
|
# JWT AUTHENTICATION
|
|
143
143
|
# ===================================================================
|
|
144
144
|
|
|
145
|
-
# CRITICAL: Generate a cryptographically secure secret
|
|
146
|
-
#
|
|
145
|
+
# CRITICAL: Generate a cryptographically secure secret: openssl rand -hex 48
|
|
146
|
+
# The value below is EXAMPLE TEXT, not a real secret. Every committed example
|
|
147
|
+
# secret starts with CHANGE_ME, and the server refuses to boot with it
|
|
148
|
+
# (src/config/env.ts), so a forgotten placeholder fails loudly.
|
|
147
149
|
# COOLIFY: Runtime only. Do NOT check "Available at Buildtime" — this is a secret!
|
|
148
|
-
JWT_SECRET="
|
|
150
|
+
JWT_SECRET="CHANGE_ME_generate_with_openssl_rand_hex_48"
|
|
149
151
|
|
|
150
152
|
# Production token expiry (tighter security)
|
|
151
153
|
JWT_ACCESS_EXPIRY="15m"
|
|
152
154
|
JWT_REFRESH_EXPIRY="7d"
|
|
153
155
|
|
|
154
|
-
# Cookie signing secret (separate from JWT for defense-in-depth)
|
|
156
|
+
# Cookie signing secret (separate from JWT for defense-in-depth).
|
|
157
|
+
# EXAMPLE TEXT: generate a different value with openssl rand -hex 48.
|
|
155
158
|
# COOLIFY: Runtime only. Do NOT check "Available at Buildtime" — this is a secret!
|
|
156
|
-
COOKIE_SECRET="
|
|
159
|
+
COOKIE_SECRET="CHANGE_ME_generate_with_openssl_rand_hex_48"
|
|
157
160
|
|
|
158
161
|
# ===================================================================
|
|
159
162
|
# CORS
|
|
@@ -167,8 +170,10 @@ CORS_ORIGIN="https://yourdomain.com,https://app.yourdomain.com"
|
|
|
167
170
|
# REQUIRED when client and API are on different subdomains:
|
|
168
171
|
# Client: https://app.example.com | API: https://api.example.com
|
|
169
172
|
# → Set COOKIE_DOMAIN=".example.com" (leading dot = all subdomains)
|
|
170
|
-
#
|
|
171
|
-
#
|
|
173
|
+
# Only the non-secret auth_session indicator uses this domain, so the client's
|
|
174
|
+
# middleware can see a session exists. The access/refresh token cookies stay
|
|
175
|
+
# host-only on the API and are never sent to other subdomains.
|
|
176
|
+
# Without it, the client keeps redirecting signed-in users to /login.
|
|
172
177
|
COOKIE_DOMAIN=".yourdomain.com"
|
|
173
178
|
|
|
174
179
|
# ===================================================================
|
|
@@ -222,7 +227,8 @@ SENTRY_ENVIRONMENT=production
|
|
|
222
227
|
# PRODUCTION CHECKLIST
|
|
223
228
|
# ===================================================================
|
|
224
229
|
# [ ] DATABASE_URL uses secure credentials and SSL
|
|
225
|
-
# [ ] JWT_SECRET is a strong random string (48
|
|
230
|
+
# [ ] JWT_SECRET is a strong random string (openssl rand -hex 48), not the CHANGE_ME example
|
|
231
|
+
# [ ] COOKIE_SECRET is a different strong random string, not the CHANGE_ME example
|
|
226
232
|
# [ ] CORS_ORIGIN is set to your exact frontend URL(s)
|
|
227
233
|
# [ ] COOKIE_DOMAIN is set if client and API are on different subdomains
|
|
228
234
|
# [ ] REDIS_URL uses authentication if Redis is exposed
|
|
@@ -87,6 +87,11 @@ RUN addgroup -g 1001 -S nodejs && \
|
|
|
87
87
|
|
|
88
88
|
WORKDIR /app
|
|
89
89
|
|
|
90
|
+
# Pin production mode in the runtime image. src/config/env.ts already defaults
|
|
91
|
+
# an unset NODE_ENV to production; this keeps the image fail-closed even if that
|
|
92
|
+
# default ever changes. A runtime NODE_ENV from Coolify still overrides it.
|
|
93
|
+
ENV NODE_ENV=production
|
|
94
|
+
|
|
90
95
|
# Copy production dependencies from dependencies stage.
|
|
91
96
|
# Includes the Prisma CLI (+ its engines) installed in stage 1, which the
|
|
92
97
|
# CMD below needs for `npx prisma migrate deploy`.
|