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
|
@@ -1,120 +1,71 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* avatar folder: every upload gets a new file, the database is pointed at it
|
|
4
|
-
* with a compare-and-swap, and only the file that swap replaced is deleted.
|
|
5
|
-
* The invariant checked throughout: afterwards the folder holds exactly the
|
|
6
|
-
* file the database names, including when two uploads race.
|
|
7
|
-
*/
|
|
8
|
-
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
9
|
-
import { usersService } from '../users.service.js';
|
|
10
|
-
import { usersRepository } from '../users.repo.js';
|
|
1
|
+
import { beforeEach, expect, it, vi } from 'vitest';
|
|
2
|
+
import { assertMutationActor } from '@libs/account-mutation.js';
|
|
11
3
|
import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
12
4
|
import { testUsers } from '@/test/setup.js';
|
|
5
|
+
import { usersService } from '../users.service.js';
|
|
6
|
+
import { usersRepository } from '../users.repo.js';
|
|
7
|
+
import { protectPendingAvatar, queueReplacedAvatar, tryAvatarCleanup } from '../avatar-cleanup.js';
|
|
13
8
|
|
|
9
|
+
const tx = vi.hoisted(() => ({ avatarCleanup: { findUnique: vi.fn(), delete: vi.fn() } }));
|
|
10
|
+
vi.mock('@libs/account-mutation.js', () => ({
|
|
11
|
+
assertMutationActor: vi.fn(),
|
|
12
|
+
runAccountMutation: async (write: (transaction: typeof tx) => Promise<unknown>): Promise<unknown> => write(tx),
|
|
13
|
+
}));
|
|
14
14
|
vi.mock('@modules/auth/auth.repo.js');
|
|
15
|
-
vi.mock('@modules/auth/session.repo.js');
|
|
16
|
-
vi.mock('@libs/password.js');
|
|
17
15
|
vi.mock('../users.repo.js');
|
|
16
|
+
vi.mock('../avatar-cleanup.js');
|
|
18
17
|
vi.mock('@libs/storage/image-optimizer.service.js', () => ({
|
|
19
|
-
imageOptimizerService: { optimizeAvatar: vi.fn(async (
|
|
18
|
+
imageOptimizerService: { optimizeAvatar: vi.fn(async (bytes: Buffer) => bytes) },
|
|
20
19
|
}));
|
|
21
|
-
vi.mock('@libs/storage/file-storage.service.js',
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const USER_ID = testUsers.validUser.id;
|
|
26
|
-
const urlOf = (file: string): string => `/uploads/users/${USER_ID}/avatar/${file}`;
|
|
20
|
+
vi.mock('@libs/storage/file-storage.service.js', async importOriginal => {
|
|
21
|
+
const actual = await importOriginal<typeof import('@libs/storage/file-storage.service.js')>();
|
|
22
|
+
return { ...actual, fileStorageService: { allocateAvatar: vi.fn(), publishAvatar: vi.fn() } };
|
|
23
|
+
});
|
|
27
24
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
25
|
+
const user = testUsers.validUser;
|
|
26
|
+
const actor = { userId: user.id, sessionId: 'fixture-session' };
|
|
27
|
+
const next = { userId: user.id, filename: 'avatar-1234567890abcdef.webp' };
|
|
28
|
+
const previous = { userId: user.id, filename: 'old.webp' };
|
|
29
|
+
const oldUrl = `/uploads/users/${user.id}/avatar/${previous.filename}`;
|
|
30
|
+
const newUrl = `/uploads/users/${user.id}/avatar/${next.filename}`;
|
|
31
|
+
const upload = (): Promise<{ avatarUrl: string }> =>
|
|
32
|
+
usersService.uploadAvatar(user.id, Buffer.from('image fixture'), 'avatar.png', actor);
|
|
34
33
|
|
|
35
34
|
beforeEach(() => {
|
|
36
|
-
vi.
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
vi.mocked(usersRepository.getUserById).mockImplementation(async () => ({ ...testUsers.validUser, avatarUrl: row.avatarUrl }) as never);
|
|
43
|
-
vi.mocked(usersRepository.swapAvatarUrl).mockImplementation(async (_id, expected, next) => {
|
|
44
|
-
if (row.avatarUrl !== expected) return false;
|
|
45
|
-
row.avatarUrl = next;
|
|
46
|
-
return true;
|
|
47
|
-
});
|
|
48
|
-
vi.mocked(fileStorageService.saveAvatar).mockImplementation(async () => {
|
|
49
|
-
const n = ++saved;
|
|
50
|
-
const filename = `avatar-${String(n).padStart(16, '0')}.webp`;
|
|
51
|
-
folder.add(filename);
|
|
52
|
-
if (holdSave?.call === n) await holdSave.until;
|
|
53
|
-
return { filename, url: urlOf(filename) };
|
|
54
|
-
});
|
|
55
|
-
vi.mocked(fileStorageService.removeAvatarFile).mockImplementation(async (_id, filename) => {
|
|
56
|
-
folder.delete(filename);
|
|
57
|
-
});
|
|
35
|
+
vi.resetAllMocks();
|
|
36
|
+
tx.avatarCleanup.findUnique.mockResolvedValue({ dueAt: new Date(Date.now() + 60_000) });
|
|
37
|
+
vi.mocked(fileStorageService.allocateAvatar).mockReturnValue(next);
|
|
38
|
+
vi.mocked(usersRepository.getUserById).mockResolvedValue({ ...user, avatarUrl: oldUrl });
|
|
39
|
+
vi.mocked(queueReplacedAvatar).mockResolvedValue(previous);
|
|
58
40
|
});
|
|
59
41
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
expect(
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
it('a first upload stores the file and points the database at it', async () => {
|
|
70
|
-
const { avatarUrl } = await upload();
|
|
71
|
-
expect(avatarUrl).toMatch(/\/avatar\/avatar-\d{16}\.webp$/);
|
|
72
|
-
expect(row.avatarUrl).toBe(avatarUrl);
|
|
73
|
-
expect(fileStorageService.removeAvatarFile).not.toHaveBeenCalled();
|
|
74
|
-
expectFolderMatchesDatabase();
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
it('a re-upload gets a NEW url and deletes the file it replaced', async () => {
|
|
78
|
-
const first = await upload();
|
|
79
|
-
const second = await upload();
|
|
80
|
-
expect(second.avatarUrl).not.toBe(first.avatarUrl);
|
|
81
|
-
expect(fileStorageService.removeAvatarFile).toHaveBeenCalledWith(USER_ID, first.avatarUrl.split('/').pop());
|
|
82
|
-
expectFolderMatchesDatabase();
|
|
83
|
-
});
|
|
84
|
-
|
|
85
|
-
it('two uploads at once end with exactly the database file', async () => {
|
|
86
|
-
await upload();
|
|
87
|
-
await Promise.all([upload(), upload()]);
|
|
88
|
-
expectFolderMatchesDatabase();
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
it('an upload that finishes while another is between writing and swapping does not delete its file', async () => {
|
|
92
|
-
await upload(); // an existing avatar both uploads will try to replace
|
|
93
|
-
let releaseSecond!: () => void;
|
|
94
|
-
holdSave = { call: 3, until: new Promise<void>((r) => { releaseSecond = r; }) };
|
|
95
|
-
|
|
96
|
-
const second = upload(); // reads the old avatar, writes, then waits before swapping
|
|
97
|
-
await vi.waitFor(() => expect(saved).toBe(2));
|
|
98
|
-
const third = upload(); // its save is held: written to disk, not yet in the database
|
|
99
|
-
await vi.waitFor(() => expect(saved).toBe(3));
|
|
100
|
-
await second; // swaps old -> second, deletes old; must leave the third file alone
|
|
101
|
-
releaseSecond();
|
|
102
|
-
await third; // swap fails (database moved on), retries, replaces second, deletes it
|
|
103
|
-
|
|
104
|
-
expectFolderMatchesDatabase();
|
|
105
|
-
expect(row.avatarUrl).toBe((await third).avatarUrl);
|
|
106
|
-
});
|
|
42
|
+
it('protects the new file before publishing and cleans only the detached file after success', async () => {
|
|
43
|
+
await expect(upload()).resolves.toEqual({ avatarUrl: newUrl });
|
|
44
|
+
expect(vi.mocked(protectPendingAvatar).mock.invocationCallOrder[0]).toBeLessThan(
|
|
45
|
+
vi.mocked(fileStorageService.publishAvatar).mock.invocationCallOrder[0]!,
|
|
46
|
+
);
|
|
47
|
+
expect(usersRepository.setAvatarUrl).toHaveBeenCalledWith(tx, user.id, newUrl);
|
|
48
|
+
expect(queueReplacedAvatar).toHaveBeenCalledWith(tx, user.id, oldUrl);
|
|
49
|
+
expect(tryAvatarCleanup).toHaveBeenCalledExactlyOnceWith(previous);
|
|
50
|
+
});
|
|
107
51
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
52
|
+
it('rejects a revoked actor before publishing and cleans up the unpublished file', async () => {
|
|
53
|
+
vi.mocked(assertMutationActor).mockRejectedValueOnce(Object.assign(new Error('Ended'), { statusCode: 401 }));
|
|
54
|
+
await expect(upload()).rejects.toMatchObject({ statusCode: 401 });
|
|
55
|
+
expect(fileStorageService.publishAvatar).not.toHaveBeenCalled();
|
|
56
|
+
expect(usersRepository.setAvatarUrl).not.toHaveBeenCalled();
|
|
57
|
+
expect(tryAvatarCleanup).toHaveBeenCalledExactlyOnceWith(next);
|
|
58
|
+
});
|
|
114
59
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
60
|
+
it('preserves the old avatar when publishing fails', async () => {
|
|
61
|
+
vi.mocked(fileStorageService.publishAvatar).mockRejectedValueOnce(new Error('disk'));
|
|
62
|
+
await expect(upload()).rejects.toThrow('disk');
|
|
63
|
+
expect(usersRepository.setAvatarUrl).not.toHaveBeenCalled();
|
|
64
|
+
expect(tryAvatarCleanup).toHaveBeenCalledExactlyOnceWith(next);
|
|
120
65
|
});
|
|
66
|
+
|
|
67
|
+
it('refuses a pending upload whose cleanup deadline has arrived', async () => {
|
|
68
|
+
tx.avatarCleanup.findUnique.mockResolvedValueOnce({ dueAt: new Date(0) });
|
|
69
|
+
await expect(upload()).rejects.toMatchObject({ statusCode: 503, code: 'AVATAR_UPLOAD_EXPIRED' });
|
|
70
|
+
expect(fileStorageService.publishAvatar).not.toHaveBeenCalled();
|
|
71
|
+
});
|
|
@@ -113,7 +113,7 @@ describe('avatar formats are judged by the bytes', () => {
|
|
|
113
113
|
});
|
|
114
114
|
|
|
115
115
|
describe('avatar files', () => {
|
|
116
|
-
it('a re-upload gets a new random name with
|
|
116
|
+
it('a re-upload gets a new random name served with no-store; the old URL is 404 at once; 1 file on disk', async () => {
|
|
117
117
|
const u = await registerUser(app, 'files');
|
|
118
118
|
const a = await uploadAvatar(app, u.jar, await image('jpeg'));
|
|
119
119
|
const b = await uploadAvatar(app, u.jar, await image('png'));
|
|
@@ -123,7 +123,7 @@ describe('avatar files', () => {
|
|
|
123
123
|
expect((await call(app, 'GET', urlA)).status).toBe(404);
|
|
124
124
|
const fresh = await call(app, 'GET', urlB);
|
|
125
125
|
expect(fresh.status).toBe(200);
|
|
126
|
-
expect(fresh.res.headers['cache-control']).toBe('
|
|
126
|
+
expect(fresh.res.headers['cache-control']).toBe('no-store');
|
|
127
127
|
expect(urlB).toMatch(/\/avatar\/avatar-[0-9a-f]{16}\.webp$/);
|
|
128
128
|
expect(await avatarUrlOf(u.id)).toBe(urlB);
|
|
129
129
|
expect(filesIn(avatarDir(u.id))).toEqual([path.basename(urlB)]);
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The two avatar-related queries in users.repo: soft delete clears the avatar
|
|
3
|
-
* URL, and the avatar
|
|
4
|
-
* deleted account.
|
|
3
|
+
* URL, and the avatar/profile writes keep the deleted-account predicate.
|
|
5
4
|
*/
|
|
6
5
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
6
|
import { prisma } from '@libs/prisma.js';
|
|
@@ -17,21 +16,19 @@ beforeEach(() => {
|
|
|
17
16
|
|
|
18
17
|
describe('usersRepository', () => {
|
|
19
18
|
it('softDeleteUser clears the avatar URL with the deletion', async () => {
|
|
20
|
-
await usersRepository.softDeleteUser('u1');
|
|
19
|
+
await usersRepository.softDeleteUser(prisma, 'u1');
|
|
21
20
|
expect(prisma.user.update).toHaveBeenCalledWith({
|
|
22
21
|
where: { id: 'u1' },
|
|
23
22
|
data: { deletedAt: expect.any(Date), isActive: false, avatarUrl: null },
|
|
24
23
|
});
|
|
25
24
|
});
|
|
26
25
|
|
|
27
|
-
it('
|
|
28
|
-
|
|
29
|
-
await
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
where: { id: 'u1', deletedAt: null, avatarUrl: '/old.webp' },
|
|
33
|
-
data: { avatarUrl: '/new.webp' },
|
|
26
|
+
it('updates the avatar and profile only for a live target in the transaction', async () => {
|
|
27
|
+
await usersRepository.setAvatarUrl(prisma, 'u1', null);
|
|
28
|
+
await usersRepository.updateUserProfile(prisma, 'u1', { firstName: 'New' });
|
|
29
|
+
expect(prisma.user.update).toHaveBeenNthCalledWith(1, {
|
|
30
|
+
where: { id: 'u1', deletedAt: null }, data: { avatarUrl: null },
|
|
34
31
|
});
|
|
35
|
-
expect(vi.mocked(prisma.user.
|
|
32
|
+
expect(vi.mocked(prisma.user.update).mock.calls[1]?.[0].where).toEqual({ id: 'u1', deletedAt: null });
|
|
36
33
|
});
|
|
37
34
|
});
|
|
@@ -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
|
+
}
|