create-tigra 4.1.0 → 5.0.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/CHANGELOG.md +16 -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/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
|
@@ -6,13 +6,14 @@
|
|
|
6
6
|
|
|
7
7
|
import type { FastifyRequest, FastifyReply } from 'fastify';
|
|
8
8
|
import { usersService } from './users.service.js';
|
|
9
|
-
import {
|
|
9
|
+
import { validateFileSize } from '@libs/storage/file-validator.js';
|
|
10
10
|
import { successResponse } from '@shared/responses/successResponse.js';
|
|
11
11
|
import { clearAuthCookies } from '@libs/cookies.js';
|
|
12
12
|
import { ChangePasswordSchema, AdminChangePasswordSchema, DeleteAccountSchema } from './users.schemas.js';
|
|
13
13
|
import type { UpdateProfileInput } from './users.schemas.js';
|
|
14
14
|
import type { AuthenticatedRequest } from '@shared/types/index.js';
|
|
15
15
|
import { logger } from '@libs/logger.js';
|
|
16
|
+
import { AppError } from '@shared/errors/AppError.js';
|
|
16
17
|
import { BadRequestError } from '@shared/errors/errors.js';
|
|
17
18
|
|
|
18
19
|
/**
|
|
@@ -32,22 +33,24 @@ class UsersController {
|
|
|
32
33
|
* @param reply - Fastify reply
|
|
33
34
|
*/
|
|
34
35
|
async uploadAvatar(request: AuthenticatedRequest, reply: FastifyReply): Promise<void> {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
36
|
+
let image: { buffer: Buffer; filename: string; mimetype: string } | undefined;
|
|
37
|
+
// The parser enforces the part, field and one-file caps throughout the form.
|
|
38
|
+
// Save only after it finishes so a limit after the image has the same effect
|
|
39
|
+
// as a limit before it. Only the bounded image buffer reaches the service.
|
|
40
|
+
for await (const part of request.parts()) {
|
|
41
|
+
if (part.type === 'field') {
|
|
42
|
+
if (part.fieldnameTruncated || part.valueTruncated) {
|
|
43
|
+
throw new AppError('MULTIPART_LIMIT', 'A form field exceeds the upload limit', 413);
|
|
44
|
+
}
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const buffer = await part.toBuffer();
|
|
48
|
+
validateFileSize(buffer, part.file.truncated);
|
|
49
|
+
image = { buffer, filename: part.filename, mimetype: part.mimetype };
|
|
40
50
|
}
|
|
41
51
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
validateImageFile(data);
|
|
45
|
-
|
|
46
|
-
// Read file buffer
|
|
47
|
-
const buffer = await data.toBuffer();
|
|
48
|
-
|
|
49
|
-
// Validate file size, including a file the parser silently cut at the limit
|
|
50
|
-
validateFileSize(buffer, data.file.truncated);
|
|
52
|
+
if (request.raw.aborted) throw new BadRequestError('Avatar upload did not finish', 'INVALID_MULTIPART');
|
|
53
|
+
if (!image) throw new BadRequestError('No file uploaded', 'NO_FILE');
|
|
51
54
|
|
|
52
55
|
// Get target user ID (set by resolveMe or resolveTargetUser middleware)
|
|
53
56
|
const userId = request.targetUserId!;
|
|
@@ -55,13 +58,13 @@ class UsersController {
|
|
|
55
58
|
logger.info({
|
|
56
59
|
msg: 'Avatar upload request',
|
|
57
60
|
userId,
|
|
58
|
-
filename:
|
|
59
|
-
mimetype:
|
|
60
|
-
size: buffer.length,
|
|
61
|
+
filename: image.filename,
|
|
62
|
+
mimetype: image.mimetype,
|
|
63
|
+
size: image.buffer.length,
|
|
61
64
|
});
|
|
62
65
|
|
|
63
66
|
// Call service to process and save avatar
|
|
64
|
-
const { avatarUrl } = await usersService.uploadAvatar(userId, buffer,
|
|
67
|
+
const { avatarUrl } = await usersService.uploadAvatar(userId, image.buffer, image.filename, request.user);
|
|
65
68
|
|
|
66
69
|
return reply.send(successResponse('Avatar uploaded successfully', { avatarUrl }));
|
|
67
70
|
}
|
|
@@ -82,7 +85,7 @@ class UsersController {
|
|
|
82
85
|
logger.info({ msg: 'Avatar delete request', userId });
|
|
83
86
|
|
|
84
87
|
// Call service to delete avatar
|
|
85
|
-
await usersService.deleteAvatar(userId);
|
|
88
|
+
await usersService.deleteAvatar(userId, request.user);
|
|
86
89
|
|
|
87
90
|
return reply.send(successResponse('Avatar deleted successfully', null));
|
|
88
91
|
}
|
|
@@ -105,7 +108,7 @@ class UsersController {
|
|
|
105
108
|
|
|
106
109
|
logger.info({ msg: 'Update profile request', userId });
|
|
107
110
|
|
|
108
|
-
const updatedUser = await usersService.updateProfile(userId, body);
|
|
111
|
+
const updatedUser = await usersService.updateProfile(userId, body, request.user);
|
|
109
112
|
|
|
110
113
|
return reply.send(successResponse('Profile updated successfully', updatedUser));
|
|
111
114
|
}
|
|
@@ -129,12 +132,12 @@ class UsersController {
|
|
|
129
132
|
if (isAdminAction) {
|
|
130
133
|
const parsed = AdminChangePasswordSchema.parse(request.body);
|
|
131
134
|
logger.info({ msg: 'Admin change password request', targetUserId: userId, adminUserId: request.user.userId });
|
|
132
|
-
await usersService.changePassword(userId, parsed,
|
|
135
|
+
await usersService.changePassword(userId, parsed, request.user);
|
|
133
136
|
} else {
|
|
134
137
|
const parsed = ChangePasswordSchema.parse(request.body);
|
|
135
138
|
logger.info({ msg: 'Change password request', userId });
|
|
136
139
|
// Keep the device that asked signed in; every other session ends.
|
|
137
|
-
await usersService.changePassword(userId, parsed,
|
|
140
|
+
await usersService.changePassword(userId, parsed, request.user);
|
|
138
141
|
}
|
|
139
142
|
|
|
140
143
|
return reply.send(successResponse('Password changed successfully', null));
|
|
@@ -158,11 +161,11 @@ class UsersController {
|
|
|
158
161
|
|
|
159
162
|
if (isAdminAction) {
|
|
160
163
|
logger.info({ msg: 'Admin delete account request', targetUserId: userId, adminUserId: request.user.userId });
|
|
161
|
-
await usersService.deleteAccount(userId,
|
|
164
|
+
await usersService.deleteAccount(userId, request.user);
|
|
162
165
|
} else {
|
|
163
166
|
const parsed = DeleteAccountSchema.parse(request.body);
|
|
164
167
|
logger.info({ msg: 'Delete account request', userId });
|
|
165
|
-
await usersService.deleteAccount(userId, parsed.password
|
|
168
|
+
await usersService.deleteAccount(userId, request.user, parsed.password);
|
|
166
169
|
}
|
|
167
170
|
|
|
168
171
|
// Only clear cookies if the user is deleting their OWN account
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Data access layer for user operations.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import {
|
|
7
|
+
import type { Prisma } from '@prisma/client';
|
|
8
8
|
import type { UserRole } from '@shared/types/index.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
@@ -45,69 +45,30 @@ class UsersRepository {
|
|
|
45
45
|
/**
|
|
46
46
|
* Gets a user by ID
|
|
47
47
|
*/
|
|
48
|
-
async getUserById(userId: string): Promise<SafeUser | null> {
|
|
49
|
-
return
|
|
48
|
+
async getUserById(userId: string, tx: Prisma.TransactionClient): Promise<SafeUser | null> {
|
|
49
|
+
return tx.user.findUnique({
|
|
50
50
|
where: { id: userId, deletedAt: null },
|
|
51
51
|
select: userSelect,
|
|
52
52
|
});
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
* the change. One counted UPDATE, so of two parallel uploads exactly one
|
|
59
|
-
* replaces any given URL, and only that one deletes the replaced file (see
|
|
60
|
-
* usersService.uploadAvatar). Deleted accounts never match.
|
|
61
|
-
*/
|
|
62
|
-
async swapAvatarUrl(userId: string, expected: string | null, next: string): Promise<boolean> {
|
|
63
|
-
const { count } = await prisma.user.updateMany({
|
|
64
|
-
where: { id: userId, deletedAt: null, avatarUrl: expected },
|
|
65
|
-
data: { avatarUrl: next },
|
|
66
|
-
});
|
|
67
|
-
return count === 1;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Clears a user's avatar URL
|
|
72
|
-
*/
|
|
73
|
-
async clearUserAvatar(userId: string): Promise<SafeUser> {
|
|
74
|
-
return prisma.user.update({
|
|
75
|
-
where: { id: userId },
|
|
76
|
-
data: { avatarUrl: null },
|
|
77
|
-
select: userSelect,
|
|
78
|
-
});
|
|
55
|
+
/** Read and write avatar state under the caller's account lock. */
|
|
56
|
+
async setAvatarUrl(tx: Prisma.TransactionClient, userId: string, avatarUrl: string | null): Promise<void> {
|
|
57
|
+
await tx.user.update({ where: { id: userId, deletedAt: null }, data: { avatarUrl } });
|
|
79
58
|
}
|
|
80
59
|
|
|
81
|
-
/**
|
|
82
|
-
* Updates a user's profile fields
|
|
83
|
-
*/
|
|
84
60
|
async updateUserProfile(
|
|
85
|
-
userId: string,
|
|
86
|
-
data: { firstName?: string; lastName?: string }
|
|
61
|
+
tx: Prisma.TransactionClient, userId: string, data: { firstName?: string; lastName?: string },
|
|
87
62
|
): Promise<SafeUser> {
|
|
88
|
-
return
|
|
89
|
-
where: { id: userId },
|
|
90
|
-
data,
|
|
91
|
-
select: userSelect,
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* How many OTHER admins could still manage the project: role ADMIN, not
|
|
97
|
-
* banned, not deleted. Zero means `userId` is the last one.
|
|
98
|
-
*/
|
|
99
|
-
async countOtherActiveAdmins(userId: string): Promise<number> {
|
|
100
|
-
return prisma.user.count({
|
|
101
|
-
where: { role: 'ADMIN', isActive: true, deletedAt: null, id: { not: userId } },
|
|
102
|
-
});
|
|
63
|
+
return tx.user.update({ where: { id: userId, deletedAt: null }, data, select: userSelect });
|
|
103
64
|
}
|
|
104
65
|
|
|
105
66
|
/**
|
|
106
|
-
* Soft
|
|
107
|
-
*
|
|
67
|
+
* Soft-deletes the user and detaches the avatar. The caller queues the
|
|
68
|
+
* detached file for cleanup in the same transaction.
|
|
108
69
|
*/
|
|
109
|
-
async softDeleteUser(userId: string): Promise<void> {
|
|
110
|
-
await
|
|
70
|
+
async softDeleteUser(tx: Prisma.TransactionClient, userId: string): Promise<void> {
|
|
71
|
+
await tx.user.update({
|
|
111
72
|
where: { id: userId },
|
|
112
73
|
data: {
|
|
113
74
|
deletedAt: new Date(),
|
|
@@ -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
|
|