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.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/bin/create-tigra.js +6 -5
  3. package/lib/patchers/email-verification.patcher.js +93 -39
  4. package/modules/email-verification/server/verification.service.ts +38 -9
  5. package/package.json +1 -1
  6. package/template/.claude/skills/security-audit/SKILL.md +10 -0
  7. package/template/AGENTS.md +18 -2
  8. package/template/CLAUDE.md +1 -0
  9. package/template/client/CLAUDE.md +1 -0
  10. package/template/client/src/features/auth/components/AuthInitializer.tsx +4 -2
  11. package/template/client/src/features/auth/components/LoginForm.tsx +5 -2
  12. package/template/client/src/features/auth/hooks/useAuth.ts +16 -6
  13. package/template/client/src/features/auth/types/auth.types.ts +3 -0
  14. package/template/client/src/instrumentation-client.ts +9 -1
  15. package/template/client/src/instrumentation.ts +6 -0
  16. package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
  17. package/template/client/src/lib/utils/error.ts +5 -1
  18. package/template/client/src/lib/utils/security.ts +37 -0
  19. package/template/server/.env.example +5 -4
  20. package/template/server/.env.example.production +14 -8
  21. package/template/server/CLAUDE.md +1 -0
  22. package/template/server/Dockerfile +5 -0
  23. package/template/server/prisma/schema.prisma +19 -3
  24. package/template/server/prisma/seed.ts +13 -5
  25. package/template/server/src/app.ts +11 -0
  26. package/template/server/src/config/env.ts +17 -6
  27. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +58 -0
  28. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +72 -58
  29. package/template/server/src/libs/__tests__/auth.test.ts +77 -0
  30. package/template/server/src/libs/__tests__/cookies.test.ts +62 -0
  31. package/template/server/src/libs/__tests__/redis.test.ts +23 -0
  32. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +80 -0
  33. package/template/server/src/libs/account-status.ts +52 -0
  34. package/template/server/src/libs/auth.ts +15 -5
  35. package/template/server/src/libs/cookies.ts +40 -12
  36. package/template/server/src/libs/ip-block.ts +3 -2
  37. package/template/server/src/libs/monitoring.ts +4 -1
  38. package/template/server/src/libs/observability/sentry.ts +80 -0
  39. package/template/server/src/libs/redis.ts +82 -18
  40. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +84 -0
  41. package/template/server/src/libs/storage/file-storage.service.ts +21 -10
  42. package/template/server/src/libs/storage/image-optimizer.service.ts +67 -72
  43. package/template/server/src/modules/admin/admin.repo.ts +7 -3
  44. package/template/server/src/modules/admin/admin.service.ts +7 -3
  45. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +136 -13
  46. package/template/server/src/modules/auth/auth.controller.ts +1 -1
  47. package/template/server/src/modules/auth/auth.repo.ts +20 -2
  48. package/template/server/src/modules/auth/auth.schemas.ts +1 -0
  49. package/template/server/src/modules/auth/auth.service.ts +30 -13
  50. package/template/server/src/modules/auth/session.repo.ts +0 -12
  51. package/template/server/src/modules/users/users.repo.ts +2 -0
  52. package/template/server/src/test/setup.ts +22 -0
@@ -0,0 +1,84 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { crc32, deflateSync } from 'node:zlib';
3
+ import sharp from 'sharp';
4
+ import { imageOptimizerService, MAX_INPUT_PIXELS } from '../image-optimizer.service.js';
5
+
6
+ // Avatars are public: the output must carry no metadata (GPS, device), and a
7
+ // small file describing a huge picture must be refused before it is decoded.
8
+
9
+ /**
10
+ * A ~70-byte PNG whose header claims width×height. Its pixel data is truncated:
11
+ * enough for the header to be read, which is exactly where the limit must act.
12
+ */
13
+ function pngHeaderOnly(width: number, height: number): Buffer {
14
+ const chunk = (type: string, data: Buffer): Buffer => {
15
+ const length = Buffer.alloc(4);
16
+ length.writeUInt32BE(data.length);
17
+ const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
18
+ const crc = Buffer.alloc(4);
19
+ crc.writeUInt32BE(crc32(body) >>> 0);
20
+ return Buffer.concat([length, body, crc]);
21
+ };
22
+ const ihdr = Buffer.alloc(13);
23
+ ihdr.writeUInt32BE(width, 0);
24
+ ihdr.writeUInt32BE(height, 4);
25
+ ihdr[8] = 8; // bit depth
26
+ ihdr[9] = 2; // colour type RGB
27
+ return Buffer.concat([
28
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
29
+ chunk('IHDR', ihdr),
30
+ chunk('IDAT', deflateSync(Buffer.alloc(64))),
31
+ chunk('IEND', Buffer.alloc(0)),
32
+ ]);
33
+ }
34
+
35
+ describe('imageOptimizerService.optimizeAvatar', () => {
36
+ it('strips EXIF/GPS/XMP and applies the orientation tag to the pixels', async () => {
37
+ const input = await sharp({ create: { width: 64, height: 32, channels: 3, background: '#808080' } })
38
+ .jpeg()
39
+ .withExif({
40
+ IFD0: { Make: 'DummyCam', Model: 'DummyModel' },
41
+ IFD3: { GPSLatitudeRef: 'N', GPSLatitude: '1/1 2/1 3/1', GPSLongitudeRef: 'E', GPSLongitude: '4/1 5/1 6/1' },
42
+ })
43
+ .withMetadata({ orientation: 6 }) // "rotate 90° clockwise" tag, as phones write it
44
+ .toBuffer();
45
+ expect((await sharp(input).metadata()).exif).toBeDefined();
46
+
47
+ const output = await imageOptimizerService.optimizeAvatar(input);
48
+ const meta = await sharp(output).metadata();
49
+
50
+ expect(meta.format).toBe('webp');
51
+ expect(meta.exif).toBeUndefined();
52
+ expect(meta.xmp).toBeUndefined();
53
+ expect(meta.orientation).toBeUndefined();
54
+ // 64×32 landscape + orientation 6 → stored upright as 32×64
55
+ expect(meta.width).toBe(32);
56
+ expect(meta.height).toBe(64);
57
+ });
58
+
59
+ it('refuses an image above the pixel limit without decoding it', async () => {
60
+ const huge = pngHeaderOnly(16000, 16000); // 256 MP claimed, a few dozen bytes
61
+ expect(16000 * 16000).toBeGreaterThan(MAX_INPUT_PIXELS);
62
+
63
+ const started = Date.now();
64
+ await expect(imageOptimizerService.optimizeAvatar(huge)).rejects.toMatchObject({ code: 'IMAGE_TOO_LARGE' });
65
+ expect(Date.now() - started).toBeLessThan(1000);
66
+ });
67
+
68
+ it('refuses formats outside the allowlist even when named like a PNG', async () => {
69
+ const gif = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#ff0000' } }).gif().toBuffer();
70
+ await expect(imageOptimizerService.optimizeAvatar(gif)).rejects.toMatchObject({
71
+ code: 'UNSUPPORTED_IMAGE_FORMAT',
72
+ });
73
+ });
74
+
75
+ it('accepts a normal photo-sized JPEG', async () => {
76
+ const photo = await sharp({ create: { width: 4000, height: 3000, channels: 3, background: '#336699' } })
77
+ .jpeg()
78
+ .toBuffer();
79
+ const output = await imageOptimizerService.optimizeAvatar(photo);
80
+ const meta = await sharp(output).metadata();
81
+ expect(meta.width).toBe(512);
82
+ expect(meta.height).toBe(384);
83
+ });
84
+ });
@@ -126,6 +126,17 @@ class FileStorageService {
126
126
  // Write file to disk (overwrites existing)
127
127
  await fs.writeFile(filePath, buffer);
128
128
 
129
+ // Remove any previous avatar files. The filename comes from the user's
130
+ // name, so after a name change the old file would otherwise stay publicly
131
+ // reachable at its old URL (possibly with metadata from before EXIF
132
+ // stripping). New file is written first, so there is never a moment with
133
+ // no avatar.
134
+ for (const entry of await fs.readdir(avatarDir)) {
135
+ if (entry !== filename) {
136
+ await fs.rm(path.join(avatarDir, entry), { force: true, recursive: true });
137
+ }
138
+ }
139
+
129
140
  // Generate public URL
130
141
  const url = `/uploads/users/${userId}/avatar/${filename}`;
131
142
 
@@ -176,10 +187,13 @@ class FileStorageService {
176
187
  }
177
188
 
178
189
  /**
179
- * Deletes all media for a user (entire user directory)
190
+ * Deletes all media for a user: the public directory (avatars) AND the
191
+ * private directory (owner-only files).
180
192
  *
181
- * Used by the cleanup job when permanently purging deleted accounts.
182
- * No-op if the user directory doesn't exist.
193
+ * Used by the cleanup job when permanently purging deleted accounts, which
194
+ * promises that nothing of the user remains. It used to delete only the
195
+ * public tier, so private files outlived the account.
196
+ * No-op for a directory that doesn't exist.
183
197
  *
184
198
  * @param userId - User's unique ID
185
199
  *
@@ -190,15 +204,12 @@ class FileStorageService {
190
204
  */
191
205
  async deleteUserMedia(userId: string): Promise<void> {
192
206
  try {
193
- const userDir = this.getUserDir(userId);
194
-
195
- const exists = await this.directoryExists(userDir);
196
- if (!exists) {
197
- return;
207
+ for (const dir of [this.getUserDir(userId), this.getUserPrivateDir(userId)]) {
208
+ if (await this.directoryExists(dir)) {
209
+ await fs.rm(dir, { recursive: true, force: true });
210
+ }
198
211
  }
199
212
 
200
- await fs.rm(userDir, { recursive: true, force: true });
201
-
202
213
  logger.info({ msg: 'User media deleted successfully', userId });
203
214
  } catch (error) {
204
215
  logger.error({ err: error, msg: 'Failed to delete user media', userId });
@@ -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. Resize to max 512x512 (preserves aspect ratio)
23
- * 2. Convert to WebP format for best compression
24
- * 3. Compress to ~85% quality
25
- * 4. Strip EXIF metadata for privacy
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
- // Validate that buffer contains a valid image
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
- // Optimize image
54
- const optimized = await sharp(buffer)
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 with quality optimization
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
- // Handle Sharp-specific errors
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
- if (error.message.includes('Input buffer contains unsupported image format')) {
83
- throw new ValidationError('Image format is not supported', 'UNSUPPORTED_IMAGE_FORMAT');
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
- if (error.message.includes('Input file is missing')) {
87
- throw new ValidationError('Invalid image data', 'INVALID_IMAGE');
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 user active status
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
- * Toggle user active status.
47
- * When deactivating, invalidates all sessions and refresh tokens.
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 updatedUser = await adminRepository.updateUserStatus(userId, isActive);
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
- isActive: true,
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 throw ForbiddenError if account is not activated', async () => {
229
- // Arrange
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.toThrow(
235
- 'Account is not activated. Please verify your account.',
236
- );
237
- expect(verifyPassword).not.toHaveBeenCalled();
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: undefined, // fixture sessionId is null → normalized to undefined
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 throw ForbiddenError if user is not activated', async () => {
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.toThrow(
445
- 'Account is not activated. Please verify your account.',
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 account to continue.', { user: result.user }),
25
+ successResponse('Registration successful. Please verify your email address to continue.', { user: result.user }),
26
26
  );
27
27
  return;
28
28
  }