create-tigra 4.0.1 → 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.
Files changed (166) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +21 -3
  3. package/bin/create-tigra.js +131 -65
  4. package/lib/installer-transaction.js +275 -0
  5. package/lib/patchers/diagnostics.patcher.js +123 -0
  6. package/lib/patchers/email-verification.patcher.js +86 -92
  7. package/lib/patchers/metrics.patcher.js +145 -0
  8. package/lib/project-files.js +99 -0
  9. package/modules/diagnostics/diagnostics.md +75 -0
  10. package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
  11. package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
  12. package/modules/diagnostics/prisma/migration.sql +20 -0
  13. package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
  14. package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
  15. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +123 -0
  16. package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
  17. package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
  18. package/modules/diagnostics/server/diagnostics.context.ts +73 -0
  19. package/modules/diagnostics/server/diagnostics.repo.ts +79 -0
  20. package/modules/diagnostics/server/diagnostics.routes.ts +16 -0
  21. package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
  22. package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
  23. package/modules/diagnostics/server/diagnostics.service.ts +44 -0
  24. package/modules/email-verification/client/hooks/useVerification.ts +4 -7
  25. package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
  26. package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
  27. package/modules/email-verification/server/verification.service.ts +102 -157
  28. package/modules/metrics/client/WebVitalsReporter.tsx +37 -0
  29. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -0
  30. package/modules/metrics/client/metrics.pages.ts +5 -0
  31. package/modules/metrics/performance.md +56 -0
  32. package/modules/metrics/prisma/metric-bucket.prisma +18 -0
  33. package/modules/metrics/prisma/migration.sql +17 -0
  34. package/modules/metrics/server/__tests__/metrics.collector.test.ts +97 -0
  35. package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
  36. package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
  37. package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
  38. package/modules/metrics/server/metrics.collector.ts +133 -0
  39. package/modules/metrics/server/metrics.pages.ts +3 -0
  40. package/modules/metrics/server/metrics.repo.ts +45 -0
  41. package/modules/metrics/server/metrics.routes.ts +45 -0
  42. package/modules/metrics/server/metrics.schemas.ts +57 -0
  43. package/modules/metrics/server/metrics.service.ts +104 -0
  44. package/package.json +1 -1
  45. package/template/AGENTS.md +18 -10
  46. package/template/client/.dockerignore +2 -5
  47. package/template/client/gitignore +43 -0
  48. package/template/client/src/app/focus-rings.policy.test.ts +88 -0
  49. package/template/client/src/app/globals.css +46 -0
  50. package/template/client/src/app/layout.tsx +5 -0
  51. package/template/client/src/app/page.tsx +2 -2
  52. package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
  53. package/template/client/src/components/ui/input.tsx +3 -2
  54. package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
  55. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  56. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  57. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  58. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  59. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  60. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  61. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  62. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  63. package/template/client/src/lib/api/axios.config.ts +24 -6
  64. package/template/client/src/lib/api/session-events.ts +54 -0
  65. package/template/client/src/lib/input-modality.test.ts +79 -0
  66. package/template/client/src/lib/input-modality.ts +52 -0
  67. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  68. package/template/client/src/store/__tests__/store.test.ts +1 -0
  69. package/template/gitignore +3 -2
  70. package/template/server/.dockerignore +2 -5
  71. package/template/server/.env.example +1 -0
  72. package/template/server/.env.example.production +1 -0
  73. package/template/server/README.md +7 -2
  74. package/template/server/docs/deployment.md +66 -0
  75. package/template/server/docs/logging.md +9 -8
  76. package/template/server/docs/rate-limits.md +6 -4
  77. package/template/server/gitignore +33 -0
  78. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  79. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  80. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  81. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  82. package/template/server/prisma/schema.prisma +25 -1
  83. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  84. package/template/server/src/app.ts +14 -5
  85. package/template/server/src/config/env.ts +8 -0
  86. package/template/server/src/config/rate-limit.config.ts +1 -1
  87. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  88. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  89. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  90. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  91. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  92. package/template/server/src/jobs/index.ts +8 -2
  93. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  94. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  95. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  96. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  97. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  98. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  99. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  100. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  101. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  102. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  103. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  104. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  105. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  106. package/template/server/src/libs/account-mutation.ts +77 -0
  107. package/template/server/src/libs/auth.ts +37 -3
  108. package/template/server/src/libs/cookies.ts +25 -13
  109. package/template/server/src/libs/email-quota.ts +11 -7
  110. package/template/server/src/libs/email.ts +11 -8
  111. package/template/server/src/libs/error-handler.ts +16 -12
  112. package/template/server/src/libs/http.ts +37 -13
  113. package/template/server/src/libs/ip-block.ts +56 -34
  114. package/template/server/src/libs/logger.ts +23 -8
  115. package/template/server/src/libs/monitoring.ts +57 -31
  116. package/template/server/src/libs/observability/sentry.ts +65 -49
  117. package/template/server/src/libs/prisma.ts +1 -1
  118. package/template/server/src/libs/private-cache.ts +6 -0
  119. package/template/server/src/libs/rate-limiting.ts +4 -0
  120. package/template/server/src/libs/requestLogger.ts +3 -3
  121. package/template/server/src/libs/safe-http.ts +58 -18
  122. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  123. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  124. package/template/server/src/libs/storage/file-validator.ts +2 -1
  125. package/template/server/src/libs/url-safety.ts +10 -2
  126. package/template/server/src/libs/validation-errors.ts +11 -8
  127. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  128. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  129. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  130. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  131. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  132. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  133. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  134. package/template/server/src/modules/admin/admin.service.ts +61 -62
  135. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  136. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  137. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  138. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  139. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  140. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  141. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  142. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  143. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  144. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  145. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  146. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  147. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  148. package/template/server/src/modules/auth/auth.service.ts +33 -237
  149. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  150. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  151. package/template/server/src/modules/auth/session.repo.ts +5 -4
  152. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  153. package/template/server/src/modules/files/files.controller.ts +2 -2
  154. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  155. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  156. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  157. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  158. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  159. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  160. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  161. package/template/server/src/modules/users/users.controller.ts +28 -25
  162. package/template/server/src/modules/users/users.repo.ts +12 -51
  163. package/template/server/src/modules/users/users.service.ts +109 -234
  164. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  165. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  166. package/template/server/src/test/setup.ts +4 -0
@@ -1,120 +1,71 @@
1
- /**
2
- * Avatar upload (usersService.uploadAvatar) against an in-memory user row and
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 (b: Buffer) => b) },
18
+ imageOptimizerService: { optimizeAvatar: vi.fn(async (bytes: Buffer) => bytes) },
20
19
  }));
21
- vi.mock('@libs/storage/file-storage.service.js', () => ({
22
- fileStorageService: { saveAvatar: vi.fn(), removeAvatarFile: vi.fn() },
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
- /** The user row's avatarUrl and the files in the avatar folder. */
29
- let row: { avatarUrl: string | null };
30
- let folder: Set<string>;
31
- let saved = 0;
32
- /** When set, the Nth saveAvatar waits for this before returning (to force an interleaving). */
33
- let holdSave: { call: number; until: Promise<unknown> } | null = null;
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.clearAllMocks();
37
- row = { avatarUrl: null };
38
- folder = new Set();
39
- saved = 0;
40
- holdSave = null;
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
- /** The invariant: the folder holds exactly the database's file. */
61
- function expectFolderMatchesDatabase(): void {
62
- expect(row.avatarUrl).not.toBeNull();
63
- expect([...folder]).toEqual([row.avatarUrl!.split('/').pop()]);
64
- }
65
-
66
- const upload = (): Promise<{ avatarUrl: string }> => usersService.uploadAvatar(USER_ID, Buffer.from('img'), 'a.png');
67
-
68
- describe('avatar upload', () => {
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
- it('a database error removes the new file and passes the error on', async () => {
109
- vi.mocked(usersRepository.swapAvatarUrl).mockRejectedValueOnce(new Error('db down'));
110
- await expect(upload()).rejects.toThrow('db down');
111
- expect(folder.size).toBe(0);
112
- expect(row.avatarUrl).toBeNull();
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
- it('an avatar that keeps changing answers 409 AVATAR_BUSY and leaves no new file', async () => {
116
- vi.mocked(usersRepository.swapAvatarUrl).mockResolvedValue(false);
117
- await expect(upload()).rejects.toMatchObject({ statusCode: 409, code: 'AVATAR_BUSY' });
118
- expect(folder.size).toBe(0);
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 a one-year cache; the old URL is 404 at once; 1 file on disk', async () => {
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('public, max-age=31536000, immutable');
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 swap is a counted compare-and-swap that never touches a
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('swapAvatarUrl changes the URL only if it is still the expected one, and says whether it did', async () => {
28
- vi.mocked(prisma.user.updateMany).mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
29
- await expect(usersRepository.swapAvatarUrl('u1', '/old.webp', '/new.webp')).resolves.toBe(true);
30
- await expect(usersRepository.swapAvatarUrl('u1', null, '/new.webp')).resolves.toBe(false);
31
- expect(prisma.user.updateMany).toHaveBeenNthCalledWith(1, {
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.updateMany).mock.calls[1]?.[0]?.where).toMatchObject({ avatarUrl: null });
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 { fileStorageService } from '@libs/storage/file-storage.service.js';
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('@modules/auth/session.repo.js');
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('@libs/storage/file-storage.service.js', () => ({ fileStorageService: { deleteAvatar: vi.fn() } }));
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(authRepo.updateUserPassword).not.toHaveBeenCalled();
37
- expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
52
+ expect(tx.user.update).not.toHaveBeenCalled();
53
+ expect(tx.session.deleteMany).not.toHaveBeenCalled();
38
54
  });
39
55
 
40
- it('changePassword with the right current password still changes it and ends all sessions', async () => {
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(authRepo.updateUserPassword).toHaveBeenCalledWith(user.id, 'new-hash');
45
- expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(user.id);
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(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(user.id);
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
- await usersService.deleteAccount(user.id, 'right');
68
- expect(fileStorageService.deleteAvatar).toHaveBeenCalledWith(user.id);
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(fileStorageService.deleteAvatar).mock.invocationCallOrder[0]).toBeGreaterThan(softDeletedAt);
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
- await usersService.deleteAccount(user.id, '', true);
75
- expect(fileStorageService.deleteAvatar).toHaveBeenCalledWith(user.id);
76
- });
77
-
78
- it('deleteAccount still succeeds when the avatar file cannot be removed (the purge retries)', async () => {
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!' }, false, 'session-here');
88
- expect(sessionRepository.deleteOtherUserSessions).toHaveBeenCalledWith(user.id, 'session-here');
89
- expect(authRepo.deleteRefreshTokensByUserId).toHaveBeenCalledWith(user.id, { exceptSessionId: 'session-here' });
90
- expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
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
- await usersService.changePassword(user.id, { newPassword: 'New-Passw0rd-123!' }, true, 'admins-own-session');
96
- expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(user.id);
97
- expect(authRepo.deleteRefreshTokensByUserId).toHaveBeenCalledWith(user.id);
98
- expect(sessionRepository.deleteOtherUserSessions).not.toHaveBeenCalled();
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
- vi.mocked(usersRepository.countOtherActiveAdmins).mockResolvedValue(0);
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
- vi.mocked(usersRepository.countOtherActiveAdmins).mockResolvedValue(1);
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(usersRepository.countOtherActiveAdmins).not.toHaveBeenCalled();
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(usersRepository.countOtherActiveAdmins).not.toHaveBeenCalled();
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
+ }