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
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
* Image Optimization Service
|
|
3
3
|
*
|
|
4
4
|
* Handles image processing, optimization, and validation using Sharp.
|
|
5
|
+
*
|
|
6
|
+
* Safety rules for user-uploaded images (avatars are public):
|
|
7
|
+
* - PRIVACY: the output carries NO metadata. sharp strips EXIF/XMP/IPTC by
|
|
8
|
+
* default; never call `.withMetadata()` / `.keepMetadata()` here — it keeps
|
|
9
|
+
* the uploader's GPS location, device and capture time in a public file.
|
|
10
|
+
* Orientation is applied to the pixels first (autoOrient) so photos don't
|
|
11
|
+
* end up sideways once the orientation tag is gone.
|
|
12
|
+
* - MEMORY: a small file can describe a huge picture (a one-colour 16k×16k
|
|
13
|
+
* PNG is ~100 KB but ~1 GB once decoded). The upload size limit only bounds
|
|
14
|
+
* the compressed bytes, so we also cap the decoded pixel count BEFORE
|
|
15
|
+
* decoding, accept only real JPEG/PNG/WebP/HEIF content (judged from the
|
|
16
|
+
* bytes, not the client's filename or MIME type), and time out slow work.
|
|
5
17
|
*/
|
|
6
18
|
|
|
7
19
|
import sharp from 'sharp';
|
|
@@ -9,6 +21,22 @@ import { FILE_UPLOAD_CONSTANTS } from './file-validator.js';
|
|
|
9
21
|
import { ValidationError, InternalError } from '@shared/errors/errors.js';
|
|
10
22
|
import { logger } from '@libs/logger.js';
|
|
11
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Largest image we agree to decode: 50 megapixels. Covers 48 MP phone photos
|
|
26
|
+
* (8064×6048); normal photos are 12–24 MP. Bounds decode memory to roughly
|
|
27
|
+
* 200 MB per upload instead of sharp's default ~1 GB (268 MP).
|
|
28
|
+
*/
|
|
29
|
+
export const MAX_INPUT_PIXELS = 50_000_000;
|
|
30
|
+
|
|
31
|
+
/** Formats sharp detects from the file's bytes that we accept for avatars. */
|
|
32
|
+
export const ALLOWED_INPUT_FORMATS = ['jpeg', 'png', 'webp', 'heif'] as const;
|
|
33
|
+
|
|
34
|
+
/** Hard stop for a single image's processing time. */
|
|
35
|
+
const PROCESSING_TIMEOUT_SECONDS = 10;
|
|
36
|
+
|
|
37
|
+
/** sharp options shared by the probe and the pipeline so both enforce the same limit. */
|
|
38
|
+
const INPUT_OPTIONS = { limitInputPixels: MAX_INPUT_PIXELS, autoOrient: true } as const;
|
|
39
|
+
|
|
12
40
|
/**
|
|
13
41
|
* Image Optimizer Service
|
|
14
42
|
*
|
|
@@ -19,29 +47,33 @@ class ImageOptimizerService {
|
|
|
19
47
|
* Optimizes an image for avatar use
|
|
20
48
|
*
|
|
21
49
|
* Process:
|
|
22
|
-
* 1.
|
|
23
|
-
* 2.
|
|
24
|
-
* 3.
|
|
25
|
-
* 4.
|
|
50
|
+
* 1. Check the real format and the pixel count before decoding
|
|
51
|
+
* 2. Apply EXIF orientation to the pixels
|
|
52
|
+
* 3. Resize to max 512x512 (preserves aspect ratio)
|
|
53
|
+
* 4. Convert to WebP (~85% quality) with ALL metadata stripped
|
|
26
54
|
*
|
|
27
55
|
* @param buffer - Original image buffer
|
|
28
56
|
* @returns Optimized image buffer in WebP format
|
|
29
|
-
* @throws ValidationError if image is invalid
|
|
30
|
-
* @throws InternalError if optimization fails
|
|
31
|
-
*
|
|
32
|
-
* @example
|
|
33
|
-
* ```typescript
|
|
34
|
-
* const optimized = await imageOptimizerService.optimizeAvatar(imageBuffer);
|
|
35
|
-
* ```
|
|
57
|
+
* @throws ValidationError if the image is invalid, too large or an unsupported format
|
|
58
|
+
* @throws InternalError if optimization fails unexpectedly
|
|
36
59
|
*/
|
|
37
60
|
async optimizeAvatar(buffer: Buffer): Promise<Buffer> {
|
|
38
61
|
try {
|
|
39
|
-
//
|
|
40
|
-
const metadata = await sharp(buffer).metadata();
|
|
62
|
+
// Reads only the header: cheap, and enforces the pixel limit up front.
|
|
63
|
+
const metadata = await sharp(buffer, INPUT_OPTIONS).metadata();
|
|
41
64
|
|
|
42
65
|
if (!metadata.width || !metadata.height) {
|
|
43
66
|
throw new ValidationError('Unable to read image dimensions', 'INVALID_IMAGE');
|
|
44
67
|
}
|
|
68
|
+
if (!metadata.format || !(ALLOWED_INPUT_FORMATS as readonly string[]).includes(metadata.format)) {
|
|
69
|
+
throw new ValidationError(
|
|
70
|
+
'Image format is not supported. Use JPEG, PNG or WebP.',
|
|
71
|
+
'UNSUPPORTED_IMAGE_FORMAT',
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
if (metadata.width * metadata.height > MAX_INPUT_PIXELS) {
|
|
75
|
+
throw new ValidationError('Image dimensions are too large', 'IMAGE_TOO_LARGE');
|
|
76
|
+
}
|
|
45
77
|
|
|
46
78
|
logger.info({
|
|
47
79
|
msg: 'Optimizing avatar image',
|
|
@@ -50,23 +82,18 @@ class ImageOptimizerService {
|
|
|
50
82
|
originalDimensions: `${metadata.width}x${metadata.height}`,
|
|
51
83
|
});
|
|
52
84
|
|
|
53
|
-
|
|
54
|
-
|
|
85
|
+
const optimized = await sharp(buffer, INPUT_OPTIONS)
|
|
86
|
+
.timeout({ seconds: PROCESSING_TIMEOUT_SECONDS })
|
|
55
87
|
// Resize to max 512x512, preserve aspect ratio
|
|
56
88
|
.resize(FILE_UPLOAD_CONSTANTS.AVATAR_MAX_DIMENSION, FILE_UPLOAD_CONSTANTS.AVATAR_MAX_DIMENSION, {
|
|
57
89
|
fit: 'inside', // Preserve aspect ratio, fit within bounds
|
|
58
90
|
withoutEnlargement: true, // Don't upscale smaller images
|
|
59
91
|
})
|
|
60
|
-
// Convert to WebP
|
|
92
|
+
// Convert to WebP. No withMetadata(): the output keeps no EXIF/GPS/XMP.
|
|
61
93
|
.webp({
|
|
62
94
|
quality: 85, // Balance between quality and file size
|
|
63
95
|
effort: 4, // Compression effort (0-6, higher = better compression but slower)
|
|
64
96
|
})
|
|
65
|
-
// Strip EXIF metadata for privacy
|
|
66
|
-
.withMetadata({
|
|
67
|
-
exif: {},
|
|
68
|
-
icc: undefined,
|
|
69
|
-
})
|
|
70
97
|
.toBuffer();
|
|
71
98
|
|
|
72
99
|
logger.info({
|
|
@@ -77,20 +104,28 @@ class ImageOptimizerService {
|
|
|
77
104
|
|
|
78
105
|
return optimized;
|
|
79
106
|
} catch (error) {
|
|
80
|
-
|
|
107
|
+
if (error instanceof ValidationError) {
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// sharp rejects bad input with plain Errors; map them to client errors.
|
|
81
112
|
if (error instanceof Error) {
|
|
82
|
-
|
|
83
|
-
|
|
113
|
+
const message = error.message.toLowerCase();
|
|
114
|
+
if (message.includes('pixel limit')) {
|
|
115
|
+
throw new ValidationError('Image dimensions are too large', 'IMAGE_TOO_LARGE');
|
|
84
116
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
117
|
+
if (message.includes('timeout')) {
|
|
118
|
+
throw new ValidationError('Image is too complex to process', 'IMAGE_TOO_COMPLEX');
|
|
119
|
+
}
|
|
120
|
+
if (
|
|
121
|
+
message.includes('unsupported image format') ||
|
|
122
|
+
message.includes('input file is missing') ||
|
|
123
|
+
message.includes('bad seek') ||
|
|
124
|
+
message.includes('corrupt') ||
|
|
125
|
+
message.includes('heif')
|
|
126
|
+
) {
|
|
127
|
+
throw new ValidationError('Invalid or unsupported image', 'INVALID_IMAGE');
|
|
88
128
|
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// Re-throw ValidationError as-is
|
|
92
|
-
if (error instanceof ValidationError) {
|
|
93
|
-
throw error;
|
|
94
129
|
}
|
|
95
130
|
|
|
96
131
|
// Wrap unexpected errors
|
|
@@ -98,46 +133,6 @@ class ImageOptimizerService {
|
|
|
98
133
|
throw new InternalError('Failed to optimize image', 'IMAGE_OPTIMIZATION_FAILED');
|
|
99
134
|
}
|
|
100
135
|
}
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* Validates that a buffer contains a valid image
|
|
104
|
-
*
|
|
105
|
-
* @param buffer - Buffer to validate
|
|
106
|
-
* @returns True if buffer is a valid image
|
|
107
|
-
* @throws ValidationError if buffer is invalid
|
|
108
|
-
*
|
|
109
|
-
* @example
|
|
110
|
-
* ```typescript
|
|
111
|
-
* await imageOptimizerService.validateImageBuffer(buffer);
|
|
112
|
-
* ```
|
|
113
|
-
*/
|
|
114
|
-
async validateImageBuffer(buffer: Buffer): Promise<boolean> {
|
|
115
|
-
try {
|
|
116
|
-
const metadata = await sharp(buffer).metadata();
|
|
117
|
-
|
|
118
|
-
if (!metadata.format || !metadata.width || !metadata.height) {
|
|
119
|
-
throw new ValidationError('Buffer does not contain a valid image', 'INVALID_IMAGE');
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// Check if format is supported
|
|
123
|
-
const supportedFormats = ['jpeg', 'png', 'webp', 'gif', 'heif'];
|
|
124
|
-
if (!supportedFormats.includes(metadata.format)) {
|
|
125
|
-
throw new ValidationError(
|
|
126
|
-
`Image format '${metadata.format}' is not supported`,
|
|
127
|
-
'UNSUPPORTED_IMAGE_FORMAT'
|
|
128
|
-
);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
return true;
|
|
132
|
-
} catch (error) {
|
|
133
|
-
if (error instanceof ValidationError) {
|
|
134
|
-
throw error;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
logger.error({ err: error, msg: 'Image validation failed' });
|
|
138
|
-
throw new ValidationError('Unable to validate image', 'INVALID_IMAGE');
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
136
|
}
|
|
142
137
|
|
|
143
138
|
// Export singleton instance
|
|
@@ -18,6 +18,7 @@ const adminUserSelect = {
|
|
|
18
18
|
role: true,
|
|
19
19
|
avatarUrl: true,
|
|
20
20
|
isActive: true,
|
|
21
|
+
emailVerifiedAt: true,
|
|
21
22
|
deletedAt: true,
|
|
22
23
|
failedLoginAttempts: true,
|
|
23
24
|
lockedUntil: true,
|
|
@@ -42,6 +43,7 @@ export type AdminUser = {
|
|
|
42
43
|
role: UserRole;
|
|
43
44
|
avatarUrl: string | null;
|
|
44
45
|
isActive: boolean;
|
|
46
|
+
emailVerifiedAt: Date | null;
|
|
45
47
|
deletedAt: Date | null;
|
|
46
48
|
failedLoginAttempts: number;
|
|
47
49
|
lockedUntil: Date | null;
|
|
@@ -180,12 +182,14 @@ class AdminRepository {
|
|
|
180
182
|
}
|
|
181
183
|
|
|
182
184
|
/**
|
|
183
|
-
* Update
|
|
185
|
+
* Update the admin ban switch (isActive).
|
|
186
|
+
* `approveEmail` also marks the email verified — used when an admin activates
|
|
187
|
+
* a user who never verified, i.e. the admin vouches for them.
|
|
184
188
|
*/
|
|
185
|
-
async updateUserStatus(userId: string, isActive: boolean): Promise<AdminUser> {
|
|
189
|
+
async updateUserStatus(userId: string, isActive: boolean, approveEmail = false): Promise<AdminUser> {
|
|
186
190
|
return prisma.user.update({
|
|
187
191
|
where: { id: userId },
|
|
188
|
-
data: { isActive },
|
|
192
|
+
data: approveEmail ? { isActive, emailVerifiedAt: new Date() } : { isActive },
|
|
189
193
|
select: adminUserSelect,
|
|
190
194
|
});
|
|
191
195
|
}
|
|
@@ -43,8 +43,11 @@ class AdminService {
|
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
/**
|
|
46
|
-
*
|
|
47
|
-
*
|
|
46
|
+
* Ban (isActive=false) or unban (isActive=true) a user.
|
|
47
|
+
* Banning invalidates all sessions and refresh tokens. A ban can only be
|
|
48
|
+
* lifted here: email verification no longer touches isActive.
|
|
49
|
+
* Activating a user who never verified their email also approves the email,
|
|
50
|
+
* so admins keep the ability to let a user in manually.
|
|
48
51
|
*/
|
|
49
52
|
async toggleUserStatus(userId: string, isActive: boolean): Promise<AdminUser> {
|
|
50
53
|
const user = await adminRepository.findUserById(userId);
|
|
@@ -53,7 +56,8 @@ class AdminService {
|
|
|
53
56
|
throw new NotFoundError('User not found');
|
|
54
57
|
}
|
|
55
58
|
|
|
56
|
-
const
|
|
59
|
+
const approveEmail = isActive && !user.emailVerifiedAt;
|
|
60
|
+
const updatedUser = await adminRepository.updateUserStatus(userId, isActive, approveEmail);
|
|
57
61
|
|
|
58
62
|
if (!isActive) {
|
|
59
63
|
// Force-logout: invalidate all sessions and refresh tokens
|
|
@@ -6,6 +6,18 @@ import { hashPassword, verifyPassword } from '@libs/password.js';
|
|
|
6
6
|
import { ConflictError, UnauthorizedError, ForbiddenError, NotFoundError } from '@shared/errors/errors.js';
|
|
7
7
|
import { testUsers, testRefreshToken, testSession, resetMocks } from '@/test/setup.js';
|
|
8
8
|
import { sessionRepository } from '../session.repo.js';
|
|
9
|
+
import { env } from '@config/env.js';
|
|
10
|
+
|
|
11
|
+
/** Run `fn` with REQUIRE_USER_VERIFICATION switched on, then restore it. */
|
|
12
|
+
async function withVerificationRequired<T>(fn: () => Promise<T>): Promise<T> {
|
|
13
|
+
const previous = env.REQUIRE_USER_VERIFICATION;
|
|
14
|
+
env.REQUIRE_USER_VERIFICATION = true;
|
|
15
|
+
try {
|
|
16
|
+
return await fn();
|
|
17
|
+
} finally {
|
|
18
|
+
env.REQUIRE_USER_VERIFICATION = previous;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
9
21
|
|
|
10
22
|
// Mock dependencies
|
|
11
23
|
vi.mock('../auth.repo.js');
|
|
@@ -38,6 +50,8 @@ describe('Auth Service', () => {
|
|
|
38
50
|
mockRedis.expire.mockResolvedValue(1);
|
|
39
51
|
mockRedis.set.mockResolvedValue('OK');
|
|
40
52
|
mockRedis.del.mockResolvedValue(1);
|
|
53
|
+
// refresh() requires the token's session to exist and be unexpired
|
|
54
|
+
vi.mocked(sessionRepository.getSessionById).mockResolvedValue(testSession);
|
|
41
55
|
});
|
|
42
56
|
|
|
43
57
|
describe('register', () => {
|
|
@@ -82,7 +96,7 @@ describe('Auth Service', () => {
|
|
|
82
96
|
password: hashedPassword,
|
|
83
97
|
firstName: validRegisterInput.firstName,
|
|
84
98
|
lastName: validRegisterInput.lastName,
|
|
85
|
-
|
|
99
|
+
emailVerifiedAt: expect.any(Date),
|
|
86
100
|
});
|
|
87
101
|
expect(authLib.signAccessToken).toHaveBeenCalledWith({
|
|
88
102
|
userId: createdUser.id,
|
|
@@ -116,6 +130,32 @@ describe('Auth Service', () => {
|
|
|
116
130
|
expect(result.user).not.toHaveProperty('password');
|
|
117
131
|
});
|
|
118
132
|
|
|
133
|
+
it('should create an unverified (but never banned) user and issue no session when verification is required', async () => {
|
|
134
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(null);
|
|
135
|
+
vi.mocked(authRepo.findDeletedUserByEmail).mockResolvedValue(null);
|
|
136
|
+
vi.mocked(hashPassword).mockResolvedValue('$2a$12$hashedpassword');
|
|
137
|
+
vi.mocked(authRepo.createUser).mockResolvedValue({
|
|
138
|
+
...testUsers.unverifiedUser,
|
|
139
|
+
email: validRegisterInput.email,
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const result = await withVerificationRequired(() => authService.register(validRegisterInput));
|
|
143
|
+
|
|
144
|
+
// isActive is not passed at all: the ban switch keeps its default (true).
|
|
145
|
+
expect(authRepo.createUser).toHaveBeenCalledWith({
|
|
146
|
+
email: validRegisterInput.email,
|
|
147
|
+
password: '$2a$12$hashedpassword',
|
|
148
|
+
firstName: validRegisterInput.firstName,
|
|
149
|
+
lastName: validRegisterInput.lastName,
|
|
150
|
+
emailVerifiedAt: null,
|
|
151
|
+
});
|
|
152
|
+
expect(result.requiresVerification).toBe(true);
|
|
153
|
+
expect(result.accessToken).toBeUndefined();
|
|
154
|
+
expect(result.user.emailVerifiedAt).toBeNull();
|
|
155
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
156
|
+
expect(sessionRepository.createSession).not.toHaveBeenCalled();
|
|
157
|
+
});
|
|
158
|
+
|
|
119
159
|
it('should throw ConflictError if email already exists', async () => {
|
|
120
160
|
// Arrange
|
|
121
161
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
@@ -225,16 +265,52 @@ describe('Auth Service', () => {
|
|
|
225
265
|
expect(authRepo.createRefreshToken).not.toHaveBeenCalled();
|
|
226
266
|
});
|
|
227
267
|
|
|
228
|
-
it('should
|
|
229
|
-
//
|
|
268
|
+
it('should not reveal that an account is banned when the password is wrong', async () => {
|
|
269
|
+
// Account state is checked only after the password, so a caller without
|
|
270
|
+
// the password gets the same answer as for any wrong password.
|
|
230
271
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.inactiveUser);
|
|
272
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
273
|
+
|
|
274
|
+
await expect(authService.login(validLoginInput)).rejects.toMatchObject({
|
|
275
|
+
code: 'INVALID_CREDENTIALS',
|
|
276
|
+
});
|
|
277
|
+
expect(verifyPassword).toHaveBeenCalled();
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
it('should reject a banned account with ACCOUNT_DEACTIVATED and issue no session', async () => {
|
|
281
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.inactiveUser);
|
|
282
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
231
283
|
|
|
232
|
-
// Act & Assert
|
|
233
284
|
await expect(authService.login(validLoginInput)).rejects.toThrow(ForbiddenError);
|
|
234
|
-
await expect(authService.login(validLoginInput)).rejects.
|
|
235
|
-
|
|
236
|
-
);
|
|
237
|
-
expect(
|
|
285
|
+
await expect(authService.login(validLoginInput)).rejects.toMatchObject({
|
|
286
|
+
code: 'ACCOUNT_DEACTIVATED',
|
|
287
|
+
});
|
|
288
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
289
|
+
expect(sessionRepository.createSession).not.toHaveBeenCalled();
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it('should reject an unverified account with EMAIL_NOT_VERIFIED while verification is required', async () => {
|
|
293
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.unverifiedUser);
|
|
294
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
295
|
+
|
|
296
|
+
await expect(
|
|
297
|
+
withVerificationRequired(() => authService.login(validLoginInput)),
|
|
298
|
+
).rejects.toMatchObject({ code: 'EMAIL_NOT_VERIFIED' });
|
|
299
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
300
|
+
expect(sessionRepository.createSession).not.toHaveBeenCalled();
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
it('should report a ban (not "verify your email") for a banned account that is also unverified', async () => {
|
|
304
|
+
// Verifying an email can never lift a ban, so the ban must win.
|
|
305
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue({
|
|
306
|
+
...testUsers.unverifiedUser,
|
|
307
|
+
isActive: false,
|
|
308
|
+
});
|
|
309
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
310
|
+
|
|
311
|
+
await expect(
|
|
312
|
+
withVerificationRequired(() => authService.login(validLoginInput)),
|
|
313
|
+
).rejects.toMatchObject({ code: 'ACCOUNT_DEACTIVATED' });
|
|
238
314
|
});
|
|
239
315
|
|
|
240
316
|
it('should throw UnauthorizedError if password is invalid', async () => {
|
|
@@ -352,6 +428,46 @@ describe('Auth Service', () => {
|
|
|
352
428
|
describe('refresh', () => {
|
|
353
429
|
const validRefreshToken = 'valid-refresh-token';
|
|
354
430
|
|
|
431
|
+
it('should reject and delete a token whose session no longer exists', async () => {
|
|
432
|
+
// e.g. the session was force-expired by an admin or removed by the cleanup job
|
|
433
|
+
vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
|
|
434
|
+
...testRefreshToken,
|
|
435
|
+
sessionId: testSession.id,
|
|
436
|
+
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
437
|
+
});
|
|
438
|
+
vi.mocked(sessionRepository.getSessionById).mockResolvedValue(null);
|
|
439
|
+
|
|
440
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'SESSION_EXPIRED' });
|
|
441
|
+
expect(authRepo.deleteRefreshToken).toHaveBeenCalledWith(validRefreshToken);
|
|
442
|
+
expect(authRepo.rotateRefreshToken).not.toHaveBeenCalled();
|
|
443
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
it('should reject a token whose session has expired', async () => {
|
|
447
|
+
vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
|
|
448
|
+
...testRefreshToken,
|
|
449
|
+
sessionId: testSession.id,
|
|
450
|
+
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
451
|
+
});
|
|
452
|
+
vi.mocked(sessionRepository.getSessionById).mockResolvedValue({
|
|
453
|
+
...testSession,
|
|
454
|
+
expiresAt: new Date(Date.now() - 1000),
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'SESSION_EXPIRED' });
|
|
458
|
+
expect(authRepo.rotateRefreshToken).not.toHaveBeenCalled();
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
it('should reject a legacy token that has no session at all', async () => {
|
|
462
|
+
vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
|
|
463
|
+
...testRefreshToken,
|
|
464
|
+
sessionId: null,
|
|
465
|
+
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'SESSION_EXPIRED' });
|
|
469
|
+
});
|
|
470
|
+
|
|
355
471
|
it('should successfully refresh tokens with valid refresh token', async () => {
|
|
356
472
|
// Arrange
|
|
357
473
|
const newAccessToken = 'new-access-token';
|
|
@@ -359,6 +475,7 @@ describe('Auth Service', () => {
|
|
|
359
475
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
|
360
476
|
const storedToken = {
|
|
361
477
|
...testRefreshToken,
|
|
478
|
+
sessionId: testSession.id,
|
|
362
479
|
token: validRefreshToken,
|
|
363
480
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // expires in 1 day
|
|
364
481
|
};
|
|
@@ -383,7 +500,7 @@ describe('Auth Service', () => {
|
|
|
383
500
|
expect(authRepo.rotateRefreshToken).toHaveBeenCalledWith(validRefreshToken, {
|
|
384
501
|
token: newRefreshToken,
|
|
385
502
|
userId: testUsers.validUser.id,
|
|
386
|
-
sessionId:
|
|
503
|
+
sessionId: testSession.id,
|
|
387
504
|
expiresAt,
|
|
388
505
|
});
|
|
389
506
|
expect(result).toEqual({
|
|
@@ -405,6 +522,7 @@ describe('Auth Service', () => {
|
|
|
405
522
|
// Arrange
|
|
406
523
|
const expiredToken = {
|
|
407
524
|
...testRefreshToken,
|
|
525
|
+
sessionId: testSession.id,
|
|
408
526
|
expiresAt: new Date(Date.now() - 1000), // expired 1 second ago
|
|
409
527
|
};
|
|
410
528
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(expiredToken);
|
|
@@ -420,6 +538,7 @@ describe('Auth Service', () => {
|
|
|
420
538
|
// Arrange
|
|
421
539
|
const storedToken = {
|
|
422
540
|
...testRefreshToken,
|
|
541
|
+
sessionId: testSession.id,
|
|
423
542
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
424
543
|
};
|
|
425
544
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
@@ -430,10 +549,11 @@ describe('Auth Service', () => {
|
|
|
430
549
|
await expect(authService.refresh(validRefreshToken)).rejects.toThrow('User not found or disabled');
|
|
431
550
|
});
|
|
432
551
|
|
|
433
|
-
it('should
|
|
552
|
+
it('should refuse to refresh a banned account', async () => {
|
|
434
553
|
// Arrange
|
|
435
554
|
const storedToken = {
|
|
436
555
|
...testRefreshToken,
|
|
556
|
+
sessionId: testSession.id,
|
|
437
557
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
438
558
|
};
|
|
439
559
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
@@ -441,9 +561,10 @@ describe('Auth Service', () => {
|
|
|
441
561
|
|
|
442
562
|
// Act & Assert
|
|
443
563
|
await expect(authService.refresh(validRefreshToken)).rejects.toThrow(ForbiddenError);
|
|
444
|
-
await expect(authService.refresh(validRefreshToken)).rejects.
|
|
445
|
-
|
|
446
|
-
);
|
|
564
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({
|
|
565
|
+
code: 'ACCOUNT_DEACTIVATED',
|
|
566
|
+
});
|
|
567
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
447
568
|
});
|
|
448
569
|
|
|
449
570
|
it('should revoke ALL refresh tokens and sessions when token reuse is detected', async () => {
|
|
@@ -454,6 +575,7 @@ describe('Auth Service', () => {
|
|
|
454
575
|
// party redeemed it first (possibly an attacker) holds a valid token.
|
|
455
576
|
const storedToken = {
|
|
456
577
|
...testRefreshToken,
|
|
578
|
+
sessionId: testSession.id,
|
|
457
579
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
458
580
|
};
|
|
459
581
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
@@ -476,6 +598,7 @@ describe('Auth Service', () => {
|
|
|
476
598
|
// the happy path.
|
|
477
599
|
const storedToken = {
|
|
478
600
|
...testRefreshToken,
|
|
601
|
+
sessionId: testSession.id,
|
|
479
602
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
480
603
|
};
|
|
481
604
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
@@ -22,7 +22,7 @@ export async function register(
|
|
|
22
22
|
|
|
23
23
|
if (result.requiresVerification) {
|
|
24
24
|
reply.status(201).send(
|
|
25
|
-
successResponse('Registration successful. Please verify your
|
|
25
|
+
successResponse('Registration successful. Please verify your email address to continue.', { user: result.user }),
|
|
26
26
|
);
|
|
27
27
|
return;
|
|
28
28
|
}
|
|
@@ -24,7 +24,8 @@ export async function createUser(data: {
|
|
|
24
24
|
password: string;
|
|
25
25
|
firstName: string;
|
|
26
26
|
lastName: string;
|
|
27
|
-
|
|
27
|
+
/** null = must verify email first; a Date = already verified. */
|
|
28
|
+
emailVerifiedAt?: Date | null;
|
|
28
29
|
}): Promise<User> {
|
|
29
30
|
return prisma.user.create({
|
|
30
31
|
data,
|
|
@@ -59,13 +60,30 @@ export async function deleteRefreshToken(token: string): Promise<void> {
|
|
|
59
60
|
}
|
|
60
61
|
}
|
|
61
62
|
|
|
63
|
+
/**
|
|
64
|
+
* Atomically swap a refresh token for a new one AND move its session forward.
|
|
65
|
+
*
|
|
66
|
+
* The session row is what users (GET /auth/sessions) and admins see and
|
|
67
|
+
* revoke, so it must stay in step with the token family: every rotation sets
|
|
68
|
+
* the session's expiresAt to the new token's expiry and refreshes lastActiveAt.
|
|
69
|
+
* Previously only the token's expiry slid forward, so after the first
|
|
70
|
+
* JWT_REFRESH_EXPIRY window a still-used login vanished from session lists and
|
|
71
|
+
* could no longer be force-expired.
|
|
72
|
+
*
|
|
73
|
+
* Returns false when the old token (or the session) is already gone — a
|
|
74
|
+
* concurrent redemption, which the caller treats as reuse.
|
|
75
|
+
*/
|
|
62
76
|
export async function rotateRefreshToken(
|
|
63
77
|
oldToken: string,
|
|
64
|
-
newData: { token: string; userId: string; sessionId
|
|
78
|
+
newData: { token: string; userId: string; sessionId: string; expiresAt: Date },
|
|
65
79
|
): Promise<boolean> {
|
|
66
80
|
try {
|
|
67
81
|
await prisma.$transaction([
|
|
68
82
|
prisma.refreshToken.delete({ where: { token: oldToken } }),
|
|
83
|
+
prisma.session.update({
|
|
84
|
+
where: { id: newData.sessionId },
|
|
85
|
+
data: { expiresAt: newData.expiresAt, lastActiveAt: new Date() },
|
|
86
|
+
}),
|
|
69
87
|
prisma.refreshToken.create({ data: newData }),
|
|
70
88
|
]);
|
|
71
89
|
return true;
|