create-tigra 4.1.0 → 5.0.1
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/CHANGELOG.md +20 -0
- package/README.md +4 -1
- package/bin/create-tigra.js +68 -73
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +33 -59
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +18 -18
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +10 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +1 -24
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
- package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
- package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
- package/modules/metrics/performance.md +2 -2
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
- package/modules/metrics/server/metrics.collector.ts +6 -3
- package/modules/metrics/server/metrics.routes.ts +1 -2
- package/modules/metrics/server/metrics.service.ts +6 -2
- package/package.json +1 -1
- package/template/AGENTS.md +4 -3
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/package-lock.json +51 -51
- package/template/client/package.json +2 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -7,234 +7,122 @@
|
|
|
7
7
|
import { usersRepository } from './users.repo.js';
|
|
8
8
|
import type { SafeUser } from './users.repo.js';
|
|
9
9
|
import * as authRepo from '@modules/auth/auth.repo.js';
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
10
|
+
import { avatarFileUrl, fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
11
|
+
import type { Prisma } from '@prisma/client';
|
|
12
|
+
import { avatarCleanupKey, protectPendingAvatar, queueReplacedAvatar, tryAvatarCleanup } from './avatar-cleanup.js';
|
|
12
13
|
import { imageOptimizerService } from '@libs/storage/image-optimizer.service.js';
|
|
13
14
|
import { verifyPassword, hashPassword } from '@libs/password.js';
|
|
14
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
assertAnotherSignInAdmin, assertMutationActor, revokeAccountCredentials, runAccountMutation,
|
|
17
|
+
type MutationActor,
|
|
18
|
+
} from '@libs/account-mutation.js';
|
|
19
|
+
import { NotFoundError, BadRequestError, ValidationError, ConflictError, ServiceUnavailableError } from '@shared/errors/errors.js';
|
|
15
20
|
import { logger } from '@libs/logger.js';
|
|
16
|
-
import path from 'path';
|
|
17
21
|
import type { UpdateProfileInput, ChangePasswordInput, AdminChangePasswordInput } from './users.schemas.js';
|
|
18
22
|
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
/** Lock before checking the target so deletion and publishing have a single order. */
|
|
24
|
+
async function lockTarget(tx: Prisma.TransactionClient, userId: string, actor: MutationActor): Promise<SafeUser> {
|
|
25
|
+
await authRepo.lockUser(tx, userId);
|
|
26
|
+
await assertMutationActor(tx, actor, actor.userId === userId ? undefined : 'ADMIN');
|
|
27
|
+
const user = await usersRepository.getUserById(userId, tx);
|
|
28
|
+
if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
29
|
+
return user;
|
|
30
|
+
}
|
|
25
31
|
|
|
26
|
-
/**
|
|
27
|
-
* Users Service Class
|
|
28
|
-
*
|
|
29
|
-
* Handles business logic for user profile and avatar operations.
|
|
30
|
-
*/
|
|
31
32
|
class UsersService {
|
|
32
|
-
/**
|
|
33
|
-
* Uploads and sets a user's avatar
|
|
34
|
-
*
|
|
35
|
-
* Process:
|
|
36
|
-
* 1. Optimize the image (bytes decide the format; WebP out, no metadata)
|
|
37
|
-
* 2. Write it under a NEW random filename (the old avatar keeps serving)
|
|
38
|
-
* 3. Point the database at it with a compare-and-swap, retrying when a
|
|
39
|
-
* parallel upload or delete changed the avatar in between
|
|
40
|
-
* 4. Delete exactly the file this swap replaced
|
|
41
|
-
*
|
|
42
|
-
* Why the swap: two uploads at once (double click, two tabs) must end with
|
|
43
|
-
* one file on disk, the one the database names. Each replaced URL is replaced
|
|
44
|
-
* by exactly one swap, and only that upload deletes its file, so no upload
|
|
45
|
-
* can delete a file another upload is about to point the database at.
|
|
46
|
-
*
|
|
47
|
-
* @param userId - User's unique ID
|
|
48
|
-
* @param fileBuffer - Uploaded image buffer
|
|
49
|
-
* @param originalFilename - Original filename (for logging)
|
|
50
|
-
* @returns The new avatar URL
|
|
51
|
-
* @throws NotFoundError if user not found
|
|
52
|
-
* @throws ConflictError (AVATAR_BUSY) if the avatar kept changing during the upload
|
|
53
|
-
*/
|
|
54
33
|
async uploadAvatar(
|
|
55
|
-
userId: string,
|
|
56
|
-
fileBuffer: Buffer,
|
|
57
|
-
originalFilename: string
|
|
34
|
+
userId: string, fileBuffer: Buffer, _originalFilename: string, actor: MutationActor,
|
|
58
35
|
): Promise<{ avatarUrl: string }> {
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
originalFilename,
|
|
68
|
-
fileSize: fileBuffer.length,
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
const optimizedBuffer = await imageOptimizerService.optimizeAvatar(fileBuffer);
|
|
72
|
-
const { filename, url } = await fileStorageService.saveAvatar(userId, optimizedBuffer);
|
|
73
|
-
|
|
74
|
-
// undefined = not swapped yet; null = swapped and there was no old avatar.
|
|
75
|
-
let replaced: string | null | undefined;
|
|
36
|
+
const optimized = await imageOptimizerService.optimizeAvatar(fileBuffer);
|
|
37
|
+
const file = fileStorageService.allocateAvatar(userId);
|
|
38
|
+
const url = avatarFileUrl(file);
|
|
39
|
+
await protectPendingAvatar(file);
|
|
40
|
+
|
|
41
|
+
// If MySQL retries after the rename, reuse this exact immutable file.
|
|
42
|
+
// The durable entry is removed only by the successful commit.
|
|
43
|
+
let published = false;
|
|
76
44
|
try {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
45
|
+
const previous = await runAccountMutation(async tx => {
|
|
46
|
+
const target = await lockTarget(tx, userId, actor);
|
|
47
|
+
const where = avatarCleanupKey(file);
|
|
48
|
+
const pending = await tx.avatarCleanup.findUnique({ where });
|
|
49
|
+
if (!pending || pending.dueAt.getTime() <= Date.now()) {
|
|
50
|
+
throw new ServiceUnavailableError('Avatar upload expired. Please try again.', 'AVATAR_UPLOAD_EXPIRED');
|
|
82
51
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
52
|
+
if (!published) {
|
|
53
|
+
await fileStorageService.publishAvatar(file, optimized);
|
|
54
|
+
published = true;
|
|
55
|
+
}
|
|
56
|
+
await usersRepository.setAvatarUrl(tx, userId, url);
|
|
57
|
+
await tx.avatarCleanup.delete({ where });
|
|
58
|
+
return queueReplacedAvatar(tx, userId, target.avatarUrl);
|
|
59
|
+
});
|
|
60
|
+
await tryAvatarCleanup(previous);
|
|
61
|
+
logger.info({ userId, avatarUrl: url }, 'Avatar uploaded');
|
|
62
|
+
return { avatarUrl: url };
|
|
87
63
|
} catch (error) {
|
|
88
|
-
await
|
|
64
|
+
await tryAvatarCleanup(file);
|
|
89
65
|
throw error;
|
|
90
66
|
}
|
|
91
|
-
if (replaced === undefined) {
|
|
92
|
-
await fileStorageService.removeAvatarFile(userId, filename);
|
|
93
|
-
throw new ConflictError('The avatar changed while uploading. Please try again.', 'AVATAR_BUSY');
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
if (replaced) {
|
|
97
|
-
await fileStorageService.removeAvatarFile(userId, path.basename(replaced));
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
logger.info({ msg: 'Avatar upload complete', userId, avatarUrl: url });
|
|
101
|
-
|
|
102
|
-
return { avatarUrl: url };
|
|
103
67
|
}
|
|
104
68
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
* @param userId - User's unique ID
|
|
115
|
-
* @throws NotFoundError if user not found
|
|
116
|
-
* @throws BadRequestError if user has no avatar to delete
|
|
117
|
-
*/
|
|
118
|
-
async deleteAvatar(userId: string): Promise<void> {
|
|
119
|
-
// Get current user
|
|
120
|
-
const user = await usersRepository.getUserById(userId);
|
|
121
|
-
if (!user) {
|
|
122
|
-
throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Check if user has an avatar
|
|
126
|
-
if (!user.avatarUrl) {
|
|
127
|
-
throw new BadRequestError('User has no avatar to delete', 'NO_AVATAR');
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
logger.info({ msg: 'Deleting user avatar', userId, avatarUrl: user.avatarUrl });
|
|
131
|
-
|
|
132
|
-
// Delete avatar directory and all contents
|
|
133
|
-
await fileStorageService.deleteAvatar(userId);
|
|
134
|
-
|
|
135
|
-
// Clear avatar URL in database
|
|
136
|
-
await usersRepository.clearUserAvatar(userId);
|
|
137
|
-
|
|
138
|
-
logger.info({ msg: 'Avatar deleted successfully', userId });
|
|
69
|
+
async deleteAvatar(userId: string, actor: MutationActor): Promise<void> {
|
|
70
|
+
const previous = await runAccountMutation(async tx => {
|
|
71
|
+
const target = await lockTarget(tx, userId, actor);
|
|
72
|
+
if (!target.avatarUrl) throw new BadRequestError('User has no avatar to delete', 'NO_AVATAR');
|
|
73
|
+
await usersRepository.setAvatarUrl(tx, userId, null);
|
|
74
|
+
return queueReplacedAvatar(tx, userId, target.avatarUrl);
|
|
75
|
+
});
|
|
76
|
+
await tryAvatarCleanup(previous);
|
|
77
|
+
logger.info({ userId }, 'Avatar deleted');
|
|
139
78
|
}
|
|
140
79
|
|
|
141
|
-
|
|
142
|
-
* Updates a user's profile
|
|
143
|
-
*
|
|
144
|
-
* @param userId - User's unique ID
|
|
145
|
-
* @param input - Fields to update (firstName, lastName)
|
|
146
|
-
* @returns Updated user
|
|
147
|
-
* @throws NotFoundError if user not found
|
|
148
|
-
*
|
|
149
|
-
* UpdateProfileSchema already guarantees at least one (trimmed, 2-100 char) field.
|
|
150
|
-
*/
|
|
151
|
-
async updateProfile(userId: string, input: UpdateProfileInput): Promise<SafeUser> {
|
|
80
|
+
async updateProfile(userId: string, input: UpdateProfileInput, actor: MutationActor): Promise<SafeUser> {
|
|
152
81
|
const { firstName, lastName } = input;
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
logger.info({
|
|
160
|
-
msg: 'Updating user profile',
|
|
161
|
-
userId,
|
|
162
|
-
fields: Object.keys(input).filter(k => input[k as keyof UpdateProfileInput] !== undefined),
|
|
82
|
+
const updatedUser = await runAccountMutation(async tx => {
|
|
83
|
+
await lockTarget(tx, userId, actor);
|
|
84
|
+
return usersRepository.updateUserProfile(tx, userId, { firstName, lastName });
|
|
163
85
|
});
|
|
164
|
-
|
|
165
|
-
const updateData: { firstName?: string; lastName?: string } = {};
|
|
166
|
-
if (firstName !== undefined) updateData.firstName = firstName;
|
|
167
|
-
if (lastName !== undefined) updateData.lastName = lastName;
|
|
168
|
-
|
|
169
|
-
const updatedUser = await usersRepository.updateUserProfile(userId, updateData);
|
|
170
|
-
|
|
171
|
-
logger.info({ msg: 'User profile updated', userId });
|
|
172
|
-
|
|
86
|
+
logger.info({ userId }, 'User profile updated');
|
|
173
87
|
return updatedUser;
|
|
174
88
|
}
|
|
175
89
|
|
|
176
|
-
/**
|
|
177
|
-
* Changes a user's password
|
|
178
|
-
*
|
|
179
|
-
* Afterwards every OTHER session of the user ends at once. The owner's own
|
|
180
|
-
* session (`keepSessionId`, the device that asked) stays signed in: ending it
|
|
181
|
-
* too dropped the user on the login page right after "Password changed".
|
|
182
|
-
* An admin-forced change (skipPasswordVerification, no keepSessionId) and a
|
|
183
|
-
* password reset (auth.service) still end every session.
|
|
184
|
-
*
|
|
185
|
-
* @param userId - User's unique ID
|
|
186
|
-
* @param input - Current and new password
|
|
187
|
-
* @param skipPasswordVerification - true for an admin acting on another user
|
|
188
|
-
* @param keepSessionId - the owner's current session (request.user.sessionId)
|
|
189
|
-
* @throws NotFoundError if user not found
|
|
190
|
-
* @throws ValidationError (422 INVALID_CURRENT_PASSWORD) if the current password is wrong
|
|
191
|
-
* @throws BadRequestError if new password same as current
|
|
192
|
-
*/
|
|
90
|
+
/** Change the password and revoke credentials as one database operation. */
|
|
193
91
|
async changePassword(
|
|
194
92
|
userId: string,
|
|
195
93
|
input: ChangePasswordInput | AdminChangePasswordInput,
|
|
196
|
-
|
|
197
|
-
keepSessionId?: string
|
|
94
|
+
actor: MutationActor,
|
|
198
95
|
): Promise<void> {
|
|
199
96
|
const user = await authRepo.findUserById(userId);
|
|
200
|
-
if (!user)
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
// treat it as an expired session and run a pointless token refresh.
|
|
209
|
-
if (!isValid) {
|
|
210
|
-
throw new ValidationError('Current password is incorrect', 'INVALID_CURRENT_PASSWORD');
|
|
211
|
-
}
|
|
97
|
+
if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
98
|
+
|
|
99
|
+
const selfChange = actor.userId === userId;
|
|
100
|
+
const invalidPassword = (): ValidationError =>
|
|
101
|
+
new ValidationError('Current password is incorrect', 'INVALID_CURRENT_PASSWORD');
|
|
102
|
+
if (selfChange) {
|
|
103
|
+
const { currentPassword } = input as ChangePasswordInput;
|
|
104
|
+
if (!currentPassword || !await verifyPassword(currentPassword, user.password)) throw invalidPassword();
|
|
212
105
|
}
|
|
213
|
-
|
|
214
|
-
const isSamePassword = await verifyPassword(input.newPassword, user.password);
|
|
215
|
-
if (isSamePassword) {
|
|
106
|
+
if (await verifyPassword(input.newPassword, user.password)) {
|
|
216
107
|
throw new BadRequestError('New password must be different from current password', 'SAME_PASSWORD');
|
|
217
108
|
}
|
|
218
109
|
|
|
219
110
|
const hashedPassword = await hashPassword(input.newPassword);
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
await
|
|
232
|
-
await
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
logger.info(
|
|
236
|
-
{ msg: 'Sessions invalidated after password change', userId, keptCurrentSession: Boolean(keep) },
|
|
237
|
-
);
|
|
111
|
+
const keep = selfChange ? actor.sessionId : undefined;
|
|
112
|
+
await runAccountMutation(async tx => {
|
|
113
|
+
// Refresh and sign-ins that already checked the old password take this
|
|
114
|
+
// same target lock. Password hashing stays outside the transaction.
|
|
115
|
+
const current = await authRepo.lockUser(tx, userId);
|
|
116
|
+
await assertMutationActor(tx, actor, selfChange ? undefined : 'ADMIN');
|
|
117
|
+
if (!current || current.deletedAt) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
118
|
+
if (current.password !== user.password) {
|
|
119
|
+
if (selfChange) throw invalidPassword();
|
|
120
|
+
throw new ConflictError('The password has changed. Please try again.', 'PASSWORD_CHANGED');
|
|
121
|
+
}
|
|
122
|
+
await tx.user.update({ where: { id: userId }, data: { password: hashedPassword } });
|
|
123
|
+
await revokeAccountCredentials(tx, userId, keep);
|
|
124
|
+
});
|
|
125
|
+
logger.info({ msg: 'Password changed and sessions invalidated', userId, keptCurrentSession: Boolean(keep) });
|
|
238
126
|
}
|
|
239
127
|
|
|
240
128
|
/**
|
|
@@ -247,52 +135,39 @@ class UsersService {
|
|
|
247
135
|
*/
|
|
248
136
|
async deleteAccount(
|
|
249
137
|
userId: string,
|
|
250
|
-
|
|
251
|
-
|
|
138
|
+
actor: MutationActor,
|
|
139
|
+
password?: string,
|
|
252
140
|
): Promise<void> {
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
if (!skipPasswordVerification) {
|
|
259
|
-
const isValid = await verifyPassword(password, user.password);
|
|
141
|
+
const selfDelete = userId === actor.userId;
|
|
142
|
+
let verifiedHash: string | undefined;
|
|
143
|
+
if (selfDelete) {
|
|
144
|
+
const user = await authRepo.findUserById(userId);
|
|
145
|
+
if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
260
146
|
// 422, not 401 (see changePassword): a wrong confirmation is wrong input.
|
|
261
|
-
if (!
|
|
147
|
+
if (!password || !await verifyPassword(password, user.password)) {
|
|
262
148
|
throw new ValidationError('Incorrect password', 'INVALID_PASSWORD');
|
|
263
149
|
}
|
|
264
|
-
|
|
265
|
-
// The last active admin deleting their own account would leave nobody
|
|
266
|
-
// able to manage the project. Checked after the password, so a wrong
|
|
267
|
-
// password still answers INVALID_PASSWORD. (An admin deleting ANOTHER
|
|
268
|
-
// admin always leaves themselves, so that path needs no check.)
|
|
269
|
-
if (user.role === 'ADMIN' && (await usersRepository.countOtherActiveAdmins(userId)) === 0) {
|
|
270
|
-
throw new ConflictError(
|
|
271
|
-
'You are the only admin. Make someone else an admin before deleting your account.',
|
|
272
|
-
'LAST_ADMIN',
|
|
273
|
-
);
|
|
274
|
-
}
|
|
150
|
+
verifiedHash = user.password;
|
|
275
151
|
}
|
|
276
152
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
153
|
+
const previous = await runAccountMutation(async tx => {
|
|
154
|
+
await assertMutationActor(tx, actor, selfDelete ? undefined : 'ADMIN');
|
|
155
|
+
const user = await tx.user.findUnique({ where: { id: userId, deletedAt: null } });
|
|
156
|
+
if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
157
|
+
// Password verification is expensive. Confirm the hash has not changed
|
|
158
|
+
// under the transaction before acting on the result.
|
|
159
|
+
if (selfDelete && user.password !== verifiedHash) {
|
|
160
|
+
throw new ValidationError('Incorrect password', 'INVALID_PASSWORD');
|
|
161
|
+
}
|
|
162
|
+
await assertAnotherSignInAdmin(tx, user);
|
|
163
|
+
await usersRepository.softDeleteUser(tx, userId);
|
|
164
|
+
await revokeAccountCredentials(tx, userId);
|
|
165
|
+
return queueReplacedAvatar(tx, userId, user.avatarUrl);
|
|
166
|
+
});
|
|
285
167
|
|
|
286
|
-
//
|
|
287
|
-
//
|
|
288
|
-
|
|
289
|
-
// Private files stay until the purge, unreachable since the owner can no
|
|
290
|
-
// longer sign in.
|
|
291
|
-
try {
|
|
292
|
-
await fileStorageService.deleteAvatar(userId);
|
|
293
|
-
} catch (error) {
|
|
294
|
-
logger.error({ err: error, msg: 'Account deleted but its public avatar could not be removed', userId });
|
|
295
|
-
}
|
|
168
|
+
// Only the detached avatar is eligible for removal. A concurrent restore
|
|
169
|
+
// and upload can publish a new file before this cleanup acquires the lock.
|
|
170
|
+
await tryAvatarCleanup(previous);
|
|
296
171
|
|
|
297
172
|
logger.info({ msg: 'User account deleted', userId });
|
|
298
173
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { MAX_PAGE } from '@shared/schemas/pagination.schema.js';
|
|
2
|
+
|
|
1
3
|
export function paginatedResponse<T>(
|
|
2
4
|
message: string,
|
|
3
5
|
items: T[],
|
|
@@ -19,7 +21,8 @@ export function paginatedResponse<T>(
|
|
|
19
21
|
};
|
|
20
22
|
};
|
|
21
23
|
} {
|
|
22
|
-
|
|
24
|
+
// Report only the pages the API accepts. totalItems still counts every match.
|
|
25
|
+
const totalPages = Math.min(MAX_PAGE, Math.ceil(totalItems / limit));
|
|
23
26
|
return {
|
|
24
27
|
success: true as const,
|
|
25
28
|
message,
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
|
|
3
|
+
// Offset lists are for browsing. A page ceiling bounds how far the database
|
|
4
|
+
// can be asked to walk before returning a page, even when limit is also large.
|
|
5
|
+
export const MAX_PAGE = 1000;
|
|
6
|
+
|
|
3
7
|
export const PaginationSchema = z.object({
|
|
4
|
-
page: z.coerce.number().int().min(1).default(1),
|
|
8
|
+
page: z.coerce.number().int().min(1).max(MAX_PAGE).default(1),
|
|
5
9
|
limit: z.coerce.number().int().min(1).max(100).default(10),
|
|
6
10
|
});
|
|
7
11
|
|
|
@@ -31,6 +31,7 @@ export const testUsers = {
|
|
|
31
31
|
isActive: true,
|
|
32
32
|
emailVerifiedAt: new Date('2024-01-01T00:00:00Z'),
|
|
33
33
|
deletedAt: null,
|
|
34
|
+
purgeStartedAt: null,
|
|
34
35
|
createdAt: new Date('2024-01-01T00:00:00Z'),
|
|
35
36
|
updatedAt: new Date('2024-01-01T00:00:00Z'),
|
|
36
37
|
},
|
|
@@ -47,6 +48,7 @@ export const testUsers = {
|
|
|
47
48
|
isActive: false,
|
|
48
49
|
emailVerifiedAt: new Date('2024-01-01T00:00:00Z'),
|
|
49
50
|
deletedAt: null,
|
|
51
|
+
purgeStartedAt: null,
|
|
50
52
|
createdAt: new Date('2024-01-01T00:00:00Z'),
|
|
51
53
|
updatedAt: new Date('2024-01-01T00:00:00Z'),
|
|
52
54
|
},
|
|
@@ -62,6 +64,7 @@ export const testUsers = {
|
|
|
62
64
|
isActive: true,
|
|
63
65
|
emailVerifiedAt: null,
|
|
64
66
|
deletedAt: null,
|
|
67
|
+
purgeStartedAt: null,
|
|
65
68
|
createdAt: new Date('2024-01-01T00:00:00Z'),
|
|
66
69
|
updatedAt: new Date('2024-01-01T00:00:00Z'),
|
|
67
70
|
},
|
|
@@ -76,6 +79,7 @@ export const testUsers = {
|
|
|
76
79
|
isActive: true,
|
|
77
80
|
emailVerifiedAt: new Date('2024-01-01T00:00:00Z'),
|
|
78
81
|
deletedAt: null,
|
|
82
|
+
purgeStartedAt: null,
|
|
79
83
|
createdAt: new Date('2024-01-01T00:00:00Z'),
|
|
80
84
|
updatedAt: new Date('2024-01-01T00:00:00Z'),
|
|
81
85
|
},
|