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
|
@@ -6,48 +6,64 @@
|
|
|
6
6
|
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
|
7
7
|
import { usersService } from '../users.service.js';
|
|
8
8
|
import * as authRepo from '@modules/auth/auth.repo.js';
|
|
9
|
-
import { sessionRepository } from '@modules/auth/session.repo.js';
|
|
10
9
|
import { usersRepository } from '../users.repo.js';
|
|
11
10
|
import { hashPassword, verifyPassword } from '@libs/password.js';
|
|
12
|
-
import {
|
|
11
|
+
import { queueReplacedAvatar, tryAvatarCleanup } from '../avatar-cleanup.js';
|
|
13
12
|
import { testUsers } from '@/test/setup.js';
|
|
13
|
+
import { prisma } from '@libs/prisma.js';
|
|
14
|
+
import { env } from '@config/env.js';
|
|
15
|
+
|
|
16
|
+
const tx = vi.hoisted(() => ({
|
|
17
|
+
user: { findUnique: vi.fn(), count: vi.fn(), update: vi.fn() },
|
|
18
|
+
session: { findFirst: vi.fn(), deleteMany: vi.fn() },
|
|
19
|
+
refreshToken: { deleteMany: vi.fn() },
|
|
20
|
+
}));
|
|
14
21
|
|
|
15
22
|
vi.mock('@modules/auth/auth.repo.js');
|
|
16
|
-
vi.mock('@
|
|
23
|
+
vi.mock('@libs/prisma.js', () => ({ prisma: { $transaction: vi.fn() }, isPrismaWriteConflict: vi.fn() }));
|
|
17
24
|
vi.mock('../users.repo.js');
|
|
18
25
|
vi.mock('@libs/password.js');
|
|
19
|
-
vi.mock('
|
|
26
|
+
vi.mock('../avatar-cleanup.js');
|
|
20
27
|
vi.mock('@libs/storage/image-optimizer.service.js', () => ({ imageOptimizerService: {} }));
|
|
21
28
|
|
|
22
29
|
const user = testUsers.validUser;
|
|
30
|
+
const actor = { userId: user.id, sessionId: 'session-here' };
|
|
31
|
+
const avatar = { userId: user.id, filename: 'avatar-fixture.webp' };
|
|
23
32
|
|
|
24
33
|
describe('users.service password confirmation', () => {
|
|
25
34
|
beforeEach(() => {
|
|
26
35
|
vi.clearAllMocks();
|
|
27
36
|
vi.mocked(authRepo.findUserById).mockResolvedValue(user);
|
|
37
|
+
vi.mocked(authRepo.lockUser).mockResolvedValue(user);
|
|
38
|
+
vi.mocked(prisma.$transaction).mockImplementation(write => write(tx as never));
|
|
39
|
+
tx.user.findUnique.mockResolvedValue(user);
|
|
40
|
+
tx.user.count.mockResolvedValue(0);
|
|
41
|
+
tx.session.findFirst.mockResolvedValue({ id: actor.sessionId });
|
|
42
|
+
tx.session.deleteMany.mockResolvedValue({ count: 1 });
|
|
28
43
|
vi.mocked(hashPassword).mockResolvedValue('new-hash');
|
|
44
|
+
vi.mocked(queueReplacedAvatar).mockResolvedValue(null);
|
|
29
45
|
});
|
|
30
46
|
|
|
31
47
|
it('changePassword with a wrong current password answers 422 INVALID_CURRENT_PASSWORD and changes nothing', async () => {
|
|
32
48
|
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
33
49
|
await expect(
|
|
34
|
-
usersService.changePassword(user.id, { currentPassword: 'wrong', newPassword: 'New-Passw0rd-123!' }),
|
|
50
|
+
usersService.changePassword(user.id, { currentPassword: 'wrong', newPassword: 'New-Passw0rd-123!' }, actor),
|
|
35
51
|
).rejects.toMatchObject({ statusCode: 422, code: 'INVALID_CURRENT_PASSWORD', message: 'Current password is incorrect' });
|
|
36
|
-
expect(
|
|
37
|
-
expect(
|
|
52
|
+
expect(tx.user.update).not.toHaveBeenCalled();
|
|
53
|
+
expect(tx.session.deleteMany).not.toHaveBeenCalled();
|
|
38
54
|
});
|
|
39
55
|
|
|
40
|
-
it('
|
|
56
|
+
it('changes the password through the transaction and retains just the requesting session', async () => {
|
|
41
57
|
// First call: current password matches; second: the new one differs from it.
|
|
42
58
|
vi.mocked(verifyPassword).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
|
|
43
|
-
await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' });
|
|
44
|
-
expect(
|
|
45
|
-
expect(
|
|
59
|
+
await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' }, actor);
|
|
60
|
+
expect(tx.user.update).toHaveBeenCalledWith({ where: { id: user.id }, data: { password: 'new-hash' } });
|
|
61
|
+
expect(tx.session.deleteMany).toHaveBeenCalledWith({ where: { userId: user.id, id: { not: actor.sessionId } } });
|
|
46
62
|
});
|
|
47
63
|
|
|
48
64
|
it('deleteAccount with a wrong password answers 422 INVALID_PASSWORD and deletes nothing', async () => {
|
|
49
65
|
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
50
|
-
await expect(usersService.deleteAccount(user.id, 'wrong')).rejects.toMatchObject({
|
|
66
|
+
await expect(usersService.deleteAccount(user.id, actor, 'wrong')).rejects.toMatchObject({
|
|
51
67
|
statusCode: 422,
|
|
52
68
|
code: 'INVALID_PASSWORD',
|
|
53
69
|
message: 'Incorrect password',
|
|
@@ -57,73 +73,129 @@ describe('users.service password confirmation', () => {
|
|
|
57
73
|
|
|
58
74
|
it('deleteAccount with the right password still soft-deletes and ends all sessions', async () => {
|
|
59
75
|
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
60
|
-
await usersService.deleteAccount(user.id, 'right');
|
|
61
|
-
expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(user.id);
|
|
62
|
-
expect(
|
|
76
|
+
await usersService.deleteAccount(user.id, actor, 'right');
|
|
77
|
+
expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(tx, user.id);
|
|
78
|
+
expect(tx.session.deleteMany).toHaveBeenCalledWith({ where: { userId: user.id } });
|
|
63
79
|
});
|
|
64
80
|
|
|
65
81
|
it('deleteAccount removes the public avatar at once, after the soft delete', async () => {
|
|
66
82
|
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
67
|
-
|
|
68
|
-
|
|
83
|
+
vi.mocked(queueReplacedAvatar).mockResolvedValueOnce(avatar);
|
|
84
|
+
await usersService.deleteAccount(user.id, actor, 'right');
|
|
85
|
+
expect(tryAvatarCleanup).toHaveBeenCalledWith(avatar);
|
|
69
86
|
const softDeletedAt = vi.mocked(usersRepository.softDeleteUser).mock.invocationCallOrder[0];
|
|
70
|
-
expect(vi.mocked(
|
|
87
|
+
expect(vi.mocked(tryAvatarCleanup).mock.invocationCallOrder[0]).toBeGreaterThan(softDeletedAt);
|
|
71
88
|
});
|
|
72
89
|
|
|
73
90
|
it('an admin deleting an account removes its public avatar too', async () => {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
80
|
-
vi.mocked(fileStorageService.deleteAvatar).mockRejectedValueOnce(new Error('disk'));
|
|
81
|
-
await expect(usersService.deleteAccount(user.id, 'right')).resolves.toBeUndefined();
|
|
82
|
-
expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(user.id);
|
|
91
|
+
const admin = { userId: 'admin-user', sessionId: 'admin-session' };
|
|
92
|
+
tx.user.findUnique.mockResolvedValueOnce({ ...user, id: admin.userId, role: 'ADMIN' });
|
|
93
|
+
vi.mocked(queueReplacedAvatar).mockResolvedValueOnce(avatar);
|
|
94
|
+
await usersService.deleteAccount(user.id, admin);
|
|
95
|
+
expect(tryAvatarCleanup).toHaveBeenCalledWith(avatar);
|
|
83
96
|
});
|
|
84
97
|
|
|
85
98
|
it("an owner's password change keeps the asking device signed in and ends every other session", async () => {
|
|
86
99
|
vi.mocked(verifyPassword).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
|
|
87
|
-
await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' },
|
|
88
|
-
expect(
|
|
89
|
-
|
|
90
|
-
|
|
100
|
+
await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' }, actor);
|
|
101
|
+
expect(tx.refreshToken.deleteMany).toHaveBeenCalledWith({ where: {
|
|
102
|
+
userId: user.id, OR: [{ sessionId: null }, { sessionId: { not: actor.sessionId } }],
|
|
103
|
+
} });
|
|
91
104
|
});
|
|
92
105
|
|
|
93
106
|
it('an admin-forced password change still ends every session of that user', async () => {
|
|
94
107
|
vi.mocked(verifyPassword).mockResolvedValue(false); // only the "same as current" check runs
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
108
|
+
tx.user.findUnique.mockResolvedValueOnce({ ...user, role: 'ADMIN' });
|
|
109
|
+
await usersService.changePassword(user.id, { newPassword: 'New-Passw0rd-123!' }, {
|
|
110
|
+
userId: 'admin', sessionId: 'admins-own-session',
|
|
111
|
+
});
|
|
112
|
+
expect(tx.session.deleteMany).toHaveBeenCalledWith({ where: { userId: user.id } });
|
|
113
|
+
expect(tx.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { userId: user.id } });
|
|
99
114
|
});
|
|
100
115
|
|
|
101
116
|
it('the last active admin cannot delete their own account (409 LAST_ADMIN), and nothing is deleted', async () => {
|
|
102
117
|
vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
|
|
118
|
+
tx.user.findUnique.mockResolvedValue({ ...user, role: 'ADMIN' });
|
|
103
119
|
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
104
|
-
|
|
105
|
-
await expect(usersService.deleteAccount(user.id, 'right')).rejects.toMatchObject({ statusCode: 409, code: 'LAST_ADMIN' });
|
|
120
|
+
await expect(usersService.deleteAccount(user.id, actor, 'right')).rejects.toMatchObject({ statusCode: 409, code: 'LAST_ADMIN' });
|
|
106
121
|
expect(usersRepository.softDeleteUser).not.toHaveBeenCalled();
|
|
107
122
|
});
|
|
108
123
|
|
|
109
124
|
it('an admin can delete their own account when another active admin exists', async () => {
|
|
110
125
|
vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
|
|
126
|
+
tx.user.findUnique.mockResolvedValue({ ...user, role: 'ADMIN' });
|
|
111
127
|
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
112
|
-
|
|
113
|
-
await usersService.deleteAccount(user.id, 'right');
|
|
114
|
-
expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(user.id);
|
|
128
|
+
tx.user.count.mockResolvedValue(1);
|
|
129
|
+
await usersService.deleteAccount(user.id, actor, 'right');
|
|
130
|
+
expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(tx, user.id);
|
|
115
131
|
});
|
|
116
132
|
|
|
117
133
|
it('a wrong password still answers 422 first, even for the last admin', async () => {
|
|
118
134
|
vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
|
|
119
135
|
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
120
|
-
await expect(usersService.deleteAccount(user.id, 'wrong')).rejects.toMatchObject({ code: 'INVALID_PASSWORD' });
|
|
121
|
-
expect(
|
|
136
|
+
await expect(usersService.deleteAccount(user.id, actor, 'wrong')).rejects.toMatchObject({ code: 'INVALID_PASSWORD' });
|
|
137
|
+
expect(tx.user.count).not.toHaveBeenCalled();
|
|
122
138
|
});
|
|
123
139
|
|
|
124
140
|
it('a normal user never triggers the admin check', async () => {
|
|
125
141
|
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
126
|
-
await usersService.deleteAccount(user.id, 'right');
|
|
127
|
-
expect(
|
|
142
|
+
await usersService.deleteAccount(user.id, actor, 'right');
|
|
143
|
+
expect(tx.user.count).not.toHaveBeenCalled();
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('checks that the password hash still matches inside the write transaction', async () => {
|
|
147
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
148
|
+
tx.user.findUnique.mockResolvedValue({ ...user, password: 'changed' });
|
|
149
|
+
await expect(usersService.deleteAccount(user.id, actor, 'right')).rejects.toMatchObject({ code: 'INVALID_PASSWORD' });
|
|
150
|
+
expect(usersRepository.softDeleteUser).not.toHaveBeenCalled();
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('only counts verified admins toward the last-admin rule when verification is required', async () => {
|
|
154
|
+
const requireVerification = env.REQUIRE_USER_VERIFICATION;
|
|
155
|
+
try {
|
|
156
|
+
env.REQUIRE_USER_VERIFICATION = true;
|
|
157
|
+
tx.user.findUnique.mockResolvedValue({ ...user, role: 'ADMIN', emailVerifiedAt: new Date() });
|
|
158
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
159
|
+
await expect(usersService.deleteAccount(user.id, actor, 'right')).rejects.toMatchObject({ code: 'LAST_ADMIN' });
|
|
160
|
+
expect(tx.user.count).toHaveBeenCalledWith({ where: {
|
|
161
|
+
id: { not: user.id }, role: 'ADMIN', isActive: true, deletedAt: null, emailVerifiedAt: { not: null },
|
|
162
|
+
} });
|
|
163
|
+
} finally {
|
|
164
|
+
env.REQUIRE_USER_VERIFICATION = requireVerification;
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
describe('profile and avatar authorization at write time', () => {
|
|
170
|
+
const operator = { userId: 'admin-user', sessionId: 'admin-session' };
|
|
171
|
+
|
|
172
|
+
beforeEach(() => {
|
|
173
|
+
vi.clearAllMocks();
|
|
174
|
+
vi.mocked(prisma.$transaction).mockImplementation(write => write(tx as never));
|
|
175
|
+
tx.user.findUnique.mockResolvedValue(user);
|
|
176
|
+
tx.session.findFirst.mockResolvedValue({ id: actor.sessionId });
|
|
177
|
+
vi.mocked(usersRepository.getUserById).mockResolvedValue(user);
|
|
178
|
+
vi.mocked(usersRepository.updateUserProfile).mockResolvedValue(user);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it('rejects a pending profile write when the actor session is gone', async () => {
|
|
182
|
+
tx.session.findFirst.mockResolvedValueOnce(null);
|
|
183
|
+
await expect(usersService.updateProfile(user.id, { firstName: 'Updated' }, actor))
|
|
184
|
+
.rejects.toMatchObject({ statusCode: 401, code: 'SESSION_EXPIRED' });
|
|
185
|
+
expect(usersRepository.updateUserProfile).not.toHaveBeenCalled();
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it('requires the current admin role before removing another account’s avatar', async () => {
|
|
189
|
+
tx.user.findUnique.mockResolvedValueOnce({ ...user, id: operator.userId, role: 'USER' });
|
|
190
|
+
await expect(usersService.deleteAvatar(user.id, operator)).rejects.toMatchObject({ statusCode: 403 });
|
|
191
|
+
expect(usersRepository.setAvatarUrl).not.toHaveBeenCalled();
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('rejects an admin profile update if the target is absent from the undeleted account lookup', async () => {
|
|
195
|
+
tx.user.findUnique.mockResolvedValueOnce({ ...user, id: operator.userId, role: 'ADMIN' });
|
|
196
|
+
vi.mocked(usersRepository.getUserById).mockResolvedValueOnce(null);
|
|
197
|
+
await expect(usersService.updateProfile(user.id, { firstName: 'Updated' }, operator))
|
|
198
|
+
.rejects.toMatchObject({ statusCode: 404, code: 'USER_NOT_FOUND' });
|
|
199
|
+
expect(usersRepository.updateUserProfile).not.toHaveBeenCalled();
|
|
128
200
|
});
|
|
129
201
|
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { FastifyInstance } from 'fastify';
|
|
2
|
+
import type { Prisma } from '@prisma/client';
|
|
3
|
+
import { startRecurringJob } from '@/jobs/schedule.js';
|
|
4
|
+
import { prisma } from '@libs/prisma.js';
|
|
5
|
+
import { runAccountMutation } from '@libs/account-mutation.js';
|
|
6
|
+
import { logger } from '@libs/logger.js';
|
|
7
|
+
import { avatarFileFromUrl, avatarFileUrl, fileStorageService, type AvatarFile } from '@libs/storage/file-storage.service.js';
|
|
8
|
+
import { lockUser } from '@modules/auth/auth.repo.js';
|
|
9
|
+
|
|
10
|
+
export function avatarCleanupKey(file: AvatarFile): Prisma.AvatarCleanupWhereUniqueInput {
|
|
11
|
+
return { userId_filename: { userId: file.userId, filename: file.filename } };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function protectPendingAvatar(file: AvatarFile): Promise<void> {
|
|
15
|
+
// This record exists independently of the publish transaction, so an
|
|
16
|
+
// interruption after writing bytes still leaves work for another replica.
|
|
17
|
+
await prisma.avatarCleanup.create({ data: { ...file, dueAt: new Date(Date.now() + 10 * 60_000) } });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function queueReplacedAvatar(
|
|
21
|
+
tx: Prisma.TransactionClient, userId: string, url: string | null,
|
|
22
|
+
): Promise<AvatarFile | null> {
|
|
23
|
+
const file = avatarFileFromUrl(userId, url);
|
|
24
|
+
if (!file) {
|
|
25
|
+
if (url) logger.warn({ userId }, 'Avatar URL does not name a local file for this account');
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
const dueAt = new Date();
|
|
29
|
+
await tx.avatarCleanup.upsert({
|
|
30
|
+
where: avatarCleanupKey(file), create: { ...file, dueAt }, update: { dueAt },
|
|
31
|
+
});
|
|
32
|
+
return file;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function tryAvatarCleanup(file: AvatarFile | null, immediate = true): Promise<void> {
|
|
36
|
+
if (!file) return;
|
|
37
|
+
try {
|
|
38
|
+
await runAccountMutation(async tx => {
|
|
39
|
+
// Writers and workers take the same owner lock before touching the
|
|
40
|
+
// queue. A locking queue read also protects entries for purged users.
|
|
41
|
+
await lockUser(tx, file.userId);
|
|
42
|
+
const [queued] = await tx.$queryRaw<{ dueAt: Date }[]>`
|
|
43
|
+
SELECT dueAt FROM avatar_cleanup
|
|
44
|
+
WHERE userId = ${file.userId} AND filename = ${file.filename} FOR UPDATE
|
|
45
|
+
`;
|
|
46
|
+
if (!queued || (!immediate && queued.dueAt.getTime() > Date.now())) return;
|
|
47
|
+
const owner = await tx.user.findUnique({ where: { id: file.userId }, select: { avatarUrl: true } });
|
|
48
|
+
if (owner?.avatarUrl !== avatarFileUrl(file)) await fileStorageService.removeAvatarFile(file);
|
|
49
|
+
await tx.avatarCleanup.delete({ where: avatarCleanupKey(file) });
|
|
50
|
+
});
|
|
51
|
+
} catch {
|
|
52
|
+
// A failed unlink keeps its durable entry. Moving its due time forward
|
|
53
|
+
// prevents this file from starving other work in the next bounded batch.
|
|
54
|
+
logger.warn({ userId: file.userId }, 'Avatar cleanup deferred');
|
|
55
|
+
await prisma.avatarCleanup.updateMany({
|
|
56
|
+
where: { userId: file.userId, filename: file.filename }, data: { dueAt: new Date(Date.now() + 60_000) },
|
|
57
|
+
}).catch(() => {});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function cleanupDueAvatars(): Promise<void> {
|
|
62
|
+
const files = await prisma.avatarCleanup.findMany({
|
|
63
|
+
where: { dueAt: { lte: new Date() } }, orderBy: [{ dueAt: 'asc' }, { userId: 'asc' }, { filename: 'asc' }], take: 50,
|
|
64
|
+
});
|
|
65
|
+
for (const file of files) await tryAvatarCleanup(file, false);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function startAvatarCleanupJob(app: FastifyInstance): void {
|
|
69
|
+
startRecurringJob(app, { name: 'avatar-cleanup', firstRunDelayMs: 60_000, intervalMs: 60_000, run: cleanupDueAvatars });
|
|
70
|
+
}
|
|
@@ -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(),
|