create-tigra 3.2.0 → 4.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 (209) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +160 -44
  4. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  5. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  6. package/modules/email-verification/server/verification.controller.ts +3 -1
  7. package/modules/email-verification/server/verification.service.ts +81 -21
  8. package/package.json +3 -2
  9. package/template/.github/dependabot.yml +47 -0
  10. package/template/.github/workflows/audit.yml +36 -0
  11. package/template/.github/workflows/ci.yml +79 -0
  12. package/template/AGENTS.md +18 -9
  13. package/template/client/.dockerignore +1 -0
  14. package/template/client/.env.example.production +13 -2
  15. package/template/client/AGENTS.md +13 -5
  16. package/template/client/Dockerfile +186 -14
  17. package/template/client/next.config.ts +1 -1
  18. package/template/client/package-lock.json +15983 -14181
  19. package/template/client/package.json +56 -48
  20. package/template/client/scripts/check-sharp.mjs +53 -0
  21. package/template/client/scripts/next-dev.cjs +5 -1
  22. package/template/client/src/__tests__/proxy.test.ts +92 -0
  23. package/template/client/src/app/healthz/route.ts +16 -0
  24. package/template/client/src/app/layout.tsx +9 -3
  25. package/template/client/src/app/page.tsx +2 -2
  26. package/template/client/src/app/providers.tsx +23 -4
  27. package/template/client/src/components/layout/Header.tsx +7 -3
  28. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  29. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  30. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  31. package/template/client/src/features/auth/components/AuthInitializer.tsx +38 -19
  32. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  33. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  34. package/template/client/src/features/auth/components/LoginForm.tsx +18 -4
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
  37. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  38. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  39. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  40. package/template/client/src/features/auth/types/auth.types.ts +3 -0
  41. package/template/client/src/instrumentation-client.ts +9 -1
  42. package/template/client/src/instrumentation.ts +6 -0
  43. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  44. package/template/client/src/lib/api/api.types.ts +14 -0
  45. package/template/client/src/lib/api/axios.config.ts +101 -15
  46. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  47. package/template/client/src/lib/api/session-events.ts +29 -0
  48. package/template/client/src/lib/constants/routes.ts +12 -0
  49. package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
  50. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  51. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  52. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  53. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  54. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  55. package/template/client/src/lib/utils/error.ts +86 -1
  56. package/template/client/src/lib/utils/form.ts +31 -0
  57. package/template/client/src/lib/utils/paths.ts +18 -0
  58. package/template/client/src/lib/utils/security.ts +37 -0
  59. package/template/client/src/lib/utils/session-marker.ts +24 -0
  60. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  61. package/template/client/src/store/__tests__/store.test.ts +44 -0
  62. package/template/client/src/store/index.ts +26 -8
  63. package/template/client/vitest.config.mts +48 -0
  64. package/template/server/.env.example +280 -269
  65. package/template/server/.env.example.production +283 -236
  66. package/template/server/AGENTS.md +13 -4
  67. package/template/server/Dockerfile +181 -14
  68. package/template/server/docker-compose.yml +4 -2
  69. package/template/server/docs/deployment.md +63 -0
  70. package/template/server/docs/logging.md +52 -4
  71. package/template/server/docs/rate-limits.md +153 -0
  72. package/template/server/docs/testing.md +63 -0
  73. package/template/server/eslint.config.mjs +19 -0
  74. package/template/server/package-lock.json +8784 -8743
  75. package/template/server/package.json +79 -75
  76. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  77. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  78. package/template/server/prisma/schema.prisma +19 -6
  79. package/template/server/prisma/seed.ts +13 -5
  80. package/template/server/scripts/check-heic.mjs +40 -0
  81. package/template/server/scripts/check-sharp.mjs +53 -0
  82. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  83. package/template/server/src/app.ts +248 -335
  84. package/template/server/src/config/__tests__/env.test.ts +219 -0
  85. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  86. package/template/server/src/config/env.ts +326 -171
  87. package/template/server/src/config/rate-limit.config.ts +157 -106
  88. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
  89. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  90. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  91. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  92. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +81 -65
  93. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  94. package/template/server/src/jobs/index.ts +12 -2
  95. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  96. package/template/server/src/jobs/schedule.ts +50 -0
  97. package/template/server/src/libs/__tests__/auth.test.ts +168 -0
  98. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  99. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  100. package/template/server/src/libs/__tests__/cookies.test.ts +113 -0
  101. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  102. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  103. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  104. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  105. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  106. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  107. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  108. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  109. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  110. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  111. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  112. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  113. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  114. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  115. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  116. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  117. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  118. package/template/server/src/libs/__tests__/redis.test.ts +59 -0
  119. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  120. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  121. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  122. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -0
  123. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  124. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  125. package/template/server/src/libs/account-status.ts +52 -0
  126. package/template/server/src/libs/auth.ts +51 -12
  127. package/template/server/src/libs/client-ip.ts +158 -77
  128. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  129. package/template/server/src/libs/cookies.ts +91 -24
  130. package/template/server/src/libs/email-quota.ts +74 -0
  131. package/template/server/src/libs/email.ts +46 -9
  132. package/template/server/src/libs/error-handler.ts +111 -0
  133. package/template/server/src/libs/health-routes.ts +53 -0
  134. package/template/server/src/libs/http.ts +139 -47
  135. package/template/server/src/libs/ip-address.ts +37 -0
  136. package/template/server/src/libs/ip-block.ts +284 -220
  137. package/template/server/src/libs/logger.ts +41 -12
  138. package/template/server/src/libs/monitoring.ts +131 -42
  139. package/template/server/src/libs/observability/sentry.ts +80 -0
  140. package/template/server/src/libs/origin-check.ts +9 -7
  141. package/template/server/src/libs/prisma.ts +47 -4
  142. package/template/server/src/libs/query-counter.ts +71 -59
  143. package/template/server/src/libs/rate-limiting.ts +110 -0
  144. package/template/server/src/libs/redis-required.ts +28 -0
  145. package/template/server/src/libs/redis.ts +108 -18
  146. package/template/server/src/libs/request-id.ts +18 -0
  147. package/template/server/src/libs/requestLogger.ts +112 -17
  148. package/template/server/src/libs/safe-http.ts +101 -0
  149. package/template/server/src/libs/shutdown.ts +87 -0
  150. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  151. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +143 -0
  152. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  153. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  154. package/template/server/src/libs/storage/file-storage.service.ts +104 -83
  155. package/template/server/src/libs/storage/file-validator.ts +48 -46
  156. package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
  157. package/template/server/src/libs/token-hash.ts +18 -0
  158. package/template/server/src/libs/url-safety.ts +127 -121
  159. package/template/server/src/libs/validation-errors.ts +86 -0
  160. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  161. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  162. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  163. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  164. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  165. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  166. package/template/server/src/modules/admin/admin.repo.ts +56 -13
  167. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  168. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  169. package/template/server/src/modules/admin/admin.service.ts +73 -7
  170. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  171. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  172. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  173. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +332 -49
  174. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  175. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  176. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  177. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  178. package/template/server/src/modules/auth/auth.repo.ts +60 -42
  179. package/template/server/src/modules/auth/auth.schemas.ts +5 -2
  180. package/template/server/src/modules/auth/auth.service.ts +197 -109
  181. package/template/server/src/modules/auth/session.repo.ts +12 -12
  182. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  183. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  184. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  185. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  186. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  187. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  188. package/template/server/src/modules/users/users.controller.ts +9 -38
  189. package/template/server/src/modules/users/users.repo.ts +25 -7
  190. package/template/server/src/modules/users/users.routes.ts +3 -22
  191. package/template/server/src/modules/users/users.schemas.ts +15 -9
  192. package/template/server/src/modules/users/users.service.ts +105 -93
  193. package/template/server/src/scripts/make-admin.ts +48 -0
  194. package/template/server/src/server.ts +48 -26
  195. package/template/server/src/shared/errors/AppError.ts +27 -1
  196. package/template/server/src/shared/errors/errors.ts +42 -5
  197. package/template/server/src/shared/responses/successResponse.ts +22 -3
  198. package/template/server/src/shared/types/index.ts +7 -0
  199. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  200. package/template/server/src/test/integration-helpers.ts +343 -0
  201. package/template/server/src/test/integration-services.ts +74 -0
  202. package/template/server/src/test/integration.global-setup.ts +144 -0
  203. package/template/server/src/test/integration.setup.ts +35 -158
  204. package/template/server/src/test/setup.ts +23 -8
  205. package/template/server/tsconfig.build.json +1 -1
  206. package/template/server/tsconfig.json +1 -0
  207. package/template/server/vitest.config.ts +17 -4
  208. package/template/server/vitest.integration.config.ts +18 -13
  209. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -0,0 +1,120 @@
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';
11
+ import { fileStorageService } from '@libs/storage/file-storage.service.js';
12
+ import { testUsers } from '@/test/setup.js';
13
+
14
+ vi.mock('@modules/auth/auth.repo.js');
15
+ vi.mock('@modules/auth/session.repo.js');
16
+ vi.mock('@libs/password.js');
17
+ vi.mock('../users.repo.js');
18
+ vi.mock('@libs/storage/image-optimizer.service.js', () => ({
19
+ imageOptimizerService: { optimizeAvatar: vi.fn(async (b: Buffer) => b) },
20
+ }));
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}`;
27
+
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;
34
+
35
+ 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
+ });
58
+ });
59
+
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
+ });
107
+
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
+ });
114
+
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
+ });
120
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Name rules at register and profile update: the name is trimmed BEFORE its
3
+ * length is checked, so blanks never become an empty name, and an update that
4
+ * sends nothing is wrong input (422 VALIDATION_FAILED naming both fields).
5
+ */
6
+ import { describe, expect, it } from 'vitest';
7
+ import { registerSchema } from '@modules/auth/auth.schemas.js';
8
+ import { UpdateProfileSchema } from '../users.schemas.js';
9
+
10
+ const base = { email: 'qa@example.test', password: 'Passw0rd-123', lastName: 'Tester' };
11
+
12
+ describe('register name rules', () => {
13
+ it.each([' ', ' a ', '\t\n'])('refuses %j as a first name', (firstName) => {
14
+ const result = registerSchema.safeParse({ ...base, firstName });
15
+ expect(result.success).toBe(false);
16
+ expect(result.error?.issues.map((i) => i.path.join('.'))).toEqual(['firstName']);
17
+ });
18
+
19
+ it('stores the trimmed name', () => {
20
+ expect(registerSchema.parse({ ...base, firstName: ' Ann ' }).firstName).toBe('Ann');
21
+ });
22
+
23
+ it('judges the length after trimming (100 letters plus spaces is fine)', () => {
24
+ expect(registerSchema.parse({ ...base, firstName: `${'a'.repeat(100)} ` }).firstName).toHaveLength(100);
25
+ });
26
+ });
27
+
28
+ describe('profile update rules', () => {
29
+ it('refuses an update with nothing in it, naming both fields', () => {
30
+ const result = UpdateProfileSchema.safeParse({});
31
+ expect(result.success).toBe(false);
32
+ expect(result.error?.issues.map((i) => i.path.join('.')).sort()).toEqual(['firstName', 'lastName']);
33
+ });
34
+
35
+ it('refuses a blank name instead of silently ignoring it', () => {
36
+ expect(UpdateProfileSchema.safeParse({ firstName: ' ' }).success).toBe(false);
37
+ });
38
+
39
+ it('accepts and trims one field', () => {
40
+ expect(UpdateProfileSchema.parse({ firstName: ' Bo ' })).toEqual({ firstName: 'Bo' });
41
+ });
42
+
43
+ it('drops fields it does not know (role cannot be set here)', () => {
44
+ expect(UpdateProfileSchema.parse({ lastName: 'Lee', role: 'ADMIN' })).toEqual({ lastName: 'Lee' });
45
+ });
46
+ });
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Users and files against a real MySQL, Redis and upload folders: what must
3
+ * stay true about profiles, avatars and account deletion (the layer 4
4
+ * hardening).
5
+ * - Names are trimmed before their length check.
6
+ * - An avatar's format is judged by its bytes (the browser's type and name
7
+ * are ignored); every upload gets a new random name with a one-year cache,
8
+ * the old file is gone at once, two uploads at once leave exactly one file,
9
+ * and the served file carries no EXIF.
10
+ * - Too many pixels → 422, too many bytes → 413, never a 500.
11
+ * - A deleted account's photo stops being public at once; the purge removes
12
+ * both upload tiers, then the row.
13
+ * - Changing your own password keeps this device signed in and ends the
14
+ * others; an admin's forced change ends them all.
15
+ * - Only the owner or an admin may change a user; private files are the
16
+ * owner's only.
17
+ */
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { crc32, deflateSync } from 'node:zlib';
21
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
22
+ import type { FastifyInstance } from 'fastify';
23
+ import { integrationServices } from '@/test/integration.setup.js';
24
+ import { TINY_HEIC_BASE64 } from '@/libs/storage/__tests__/fixtures/tiny-heic.js';
25
+ import {
26
+ PASSWORD,
27
+ buildTestApp,
28
+ call,
29
+ db,
30
+ image,
31
+ registerAdmin,
32
+ registerUser,
33
+ signIn,
34
+ uniqueEmail,
35
+ uploadAvatar,
36
+ type TestUser,
37
+ } from '@/test/integration-helpers.js';
38
+
39
+ let app: FastifyInstance;
40
+ let admin: TestUser;
41
+
42
+ beforeAll(async () => {
43
+ app = await buildTestApp();
44
+ admin = await registerAdmin(app, 'users-admin');
45
+ });
46
+
47
+ afterAll(async () => {
48
+ await app?.close();
49
+ });
50
+
51
+ const avatarDir = (userId: string): string => path.join(integrationServices.uploadPublicDir, 'users', userId, 'avatar');
52
+ const filesIn = (dir: string): string[] => (fs.existsSync(dir) ? fs.readdirSync(dir).sort() : []);
53
+ const avatarUrlOf = async (userId: string): Promise<string | null> =>
54
+ (await (await db()).user.findUnique({ where: { id: userId }, select: { avatarUrl: true } }))?.avatarUrl ?? null;
55
+ const isWebp = (bytes: Buffer): boolean => bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP';
56
+
57
+ describe('names', () => {
58
+ const base = { password: PASSWORD, lastName: 'Tester' };
59
+
60
+ it('register with a blank or 1-letter first name (after trimming) → 422 naming firstName', async () => {
61
+ const blank = await call(app, 'POST', '/auth/register', { payload: { ...base, email: uniqueEmail('blank'), firstName: ' ' } });
62
+ expect([blank.status, blank.code]).toEqual([422, 'VALIDATION_FAILED']);
63
+ expect(blank.body?.error?.fields?.map((f) => f.field)).toContain('firstName');
64
+ const one = await call(app, 'POST', '/auth/register', { payload: { ...base, email: uniqueEmail('one'), firstName: ' a ' } });
65
+ expect(one.status).toBe(422);
66
+ });
67
+
68
+ it('register " Ann " → 201 and stored trimmed', async () => {
69
+ const email = uniqueEmail('ann');
70
+ const r = await call(app, 'POST', '/auth/register', { payload: { ...base, email, firstName: ' Ann ' } });
71
+ expect(r.status).toBe(201);
72
+ expect((await (await db()).user.findUnique({ where: { email } }))?.firstName).toBe('Ann');
73
+ });
74
+
75
+ it('PATCH /users/me with nothing → 422 naming both fields; " Bo " → saved "Bo"', async () => {
76
+ const u = await registerUser(app, 'names');
77
+ const empty = await call(app, 'PATCH', '/users/me', { jar: u.jar, payload: {} });
78
+ expect([empty.status, empty.code]).toEqual([422, 'VALIDATION_FAILED']);
79
+ expect(empty.body?.error?.fields?.map((f) => f.field).sort()).toEqual(['firstName', 'lastName']);
80
+ const bo = await call(app, 'PATCH', '/users/me', { jar: u.jar, payload: { firstName: ' Bo ' } });
81
+ expect([bo.status, bo.body?.data?.firstName]).toEqual([200, 'Bo']);
82
+ });
83
+ });
84
+
85
+ describe('avatar formats are judged by the bytes', () => {
86
+ let u: TestUser;
87
+ beforeAll(async () => {
88
+ u = await registerUser(app, 'formats');
89
+ });
90
+
91
+ it.each(['jpeg', 'png', 'webp', 'avif'] as const)('%s sent as application/octet-stream named "blob" → 200', async (format) => {
92
+ const r = await uploadAvatar(app, u.jar, await image(format));
93
+ expect(r.status).toBe(200);
94
+ });
95
+
96
+ it('PNG bytes named photo.exe → 200, and the served file is WebP', async () => {
97
+ const r = await uploadAvatar(app, u.jar, await image('png'), { filename: 'photo.exe', type: 'application/x-msdownload' });
98
+ expect(r.status).toBe(200);
99
+ const served = await call(app, 'GET', r.body?.data?.avatarUrl);
100
+ expect(isWebp(served.res.rawPayload)).toBe(true);
101
+ });
102
+
103
+ it('text bytes named photo.jpg (image/jpeg) → 422', async () => {
104
+ const r = await uploadAvatar(app, u.jar, Buffer.from('this is not an image at all'), { filename: 'photo.jpg', type: 'image/jpeg' });
105
+ expect(r.status).toBe(422);
106
+ });
107
+
108
+ it('HEIC → 200 where this sharp can decode HEVC, otherwise 422 UNSUPPORTED_IMAGE_FORMAT; never a 500', async () => {
109
+ const r = await uploadAvatar(app, u.jar, Buffer.from(TINY_HEIC_BASE64, 'base64'), { filename: 'IMG_0001.HEIC' });
110
+ if (r.status === 422) expect(r.code).toBe('UNSUPPORTED_IMAGE_FORMAT');
111
+ else expect(r.status).toBe(200);
112
+ });
113
+ });
114
+
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 () => {
117
+ const u = await registerUser(app, 'files');
118
+ const a = await uploadAvatar(app, u.jar, await image('jpeg'));
119
+ const b = await uploadAvatar(app, u.jar, await image('png'));
120
+ const urlA = a.body?.data?.avatarUrl as string;
121
+ const urlB = b.body?.data?.avatarUrl as string;
122
+ expect(urlA).not.toBe(urlB);
123
+ expect((await call(app, 'GET', urlA)).status).toBe(404);
124
+ const fresh = await call(app, 'GET', urlB);
125
+ expect(fresh.status).toBe(200);
126
+ expect(fresh.res.headers['cache-control']).toBe('public, max-age=31536000, immutable');
127
+ expect(urlB).toMatch(/\/avatar\/avatar-[0-9a-f]{16}\.webp$/);
128
+ expect(await avatarUrlOf(u.id)).toBe(urlB);
129
+ expect(filesIn(avatarDir(u.id))).toEqual([path.basename(urlB)]);
130
+ });
131
+
132
+ it('two uploads at the same instant (6 rounds) → exactly 1 file, the one the database points at, served 200', async () => {
133
+ const u = await registerUser(app, 'race');
134
+ for (let round = 0; round < 6; round++) {
135
+ const [r1, r2] = await Promise.all([
136
+ uploadAvatar(app, u.jar, await image('jpeg', 60 + round)),
137
+ uploadAvatar(app, u.jar, await image('png', 70 + round)),
138
+ ]);
139
+ expect([r1.status, r2.status]).toEqual([200, 200]);
140
+ const current = (await avatarUrlOf(u.id)) as string;
141
+ expect(filesIn(avatarDir(u.id))).toEqual([path.basename(current)]);
142
+ expect((await call(app, 'GET', current)).status).toBe(200);
143
+ }
144
+ });
145
+
146
+ it('the served file carries no EXIF (a JPEG with GPS comes back as WebP without it)', async () => {
147
+ const u = await registerUser(app, 'gps');
148
+ const sharp = (await import('sharp')).default;
149
+ const gps = await sharp({ create: { width: 64, height: 32, channels: 3, background: '#808080' } })
150
+ .jpeg()
151
+ .withExif({ IFD0: { Make: 'DummyCam' }, IFD3: { GPSLatitudeRef: 'N', GPSLatitude: '1/1 2/1 3/1', GPSLongitudeRef: 'E', GPSLongitude: '4/1 5/1 6/1' } })
152
+ .toBuffer();
153
+ const up = await uploadAvatar(app, u.jar, gps, { filename: 'gps.jpg', type: 'image/jpeg' });
154
+ const meta = await sharp((await call(app, 'GET', up.body?.data?.avatarUrl)).res.rawPayload).metadata();
155
+ expect([meta.format, meta.exif]).toEqual(['webp', undefined]);
156
+ });
157
+
158
+ it('the old GET /api/v1/users/:id/avatar route is gone → 404', async () => {
159
+ const u = await registerUser(app, 'oldroute');
160
+ expect((await call(app, 'GET', `/users/${u.id}/avatar`)).status).toBe(404);
161
+ });
162
+
163
+ it('avatar delete → folder gone, URL 404, avatarUrl NULL', async () => {
164
+ const u = await registerUser(app, 'avdel');
165
+ const url = (await uploadAvatar(app, u.jar, await image('png'))).body?.data?.avatarUrl as string;
166
+ expect((await call(app, 'DELETE', '/users/avatar', { jar: u.jar })).status).toBe(200);
167
+ expect(fs.existsSync(avatarDir(u.id))).toBe(false);
168
+ expect((await call(app, 'GET', url)).status).toBe(404);
169
+ expect(await avatarUrlOf(u.id)).toBeNull();
170
+ });
171
+ });
172
+
173
+ describe('upload limits', () => {
174
+ it('a 60 MP PNG → 422 IMAGE_TOO_LARGE (refused from its header, never decoded)', async () => {
175
+ const u = await registerUser(app, 'pixels');
176
+ const chunk = (type: string, data: Buffer): Buffer => {
177
+ const len = Buffer.alloc(4);
178
+ len.writeUInt32BE(data.length);
179
+ const body = Buffer.concat([Buffer.from(type), data]);
180
+ const crc = Buffer.alloc(4);
181
+ crc.writeUInt32BE(crc32(body) >>> 0);
182
+ return Buffer.concat([len, body, crc]);
183
+ };
184
+ const ihdr = Buffer.alloc(13);
185
+ ihdr.writeUInt32BE(8000, 0);
186
+ ihdr.writeUInt32BE(7500, 4);
187
+ ihdr[8] = 8;
188
+ ihdr[9] = 2;
189
+ const huge = Buffer.concat([
190
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
191
+ chunk('IHDR', ihdr),
192
+ chunk('IDAT', deflateSync(Buffer.alloc(64))),
193
+ chunk('IEND', Buffer.alloc(0)),
194
+ ]);
195
+ const r = await uploadAvatar(app, u.jar, huge, { filename: 'huge.png', type: 'image/png' });
196
+ expect([r.status, r.code]).toEqual([422, 'IMAGE_TOO_LARGE']);
197
+ });
198
+
199
+ it('an 11 MB file → 413 FILE_TOO_LARGE', async () => {
200
+ const u = await registerUser(app, 'bytes');
201
+ const r = await uploadAvatar(app, u.jar, Buffer.alloc(11 * 1024 * 1024, 7), { filename: 'big.jpg', type: 'image/jpeg' });
202
+ expect([r.status, r.code]).toEqual([413, 'FILE_TOO_LARGE']);
203
+ });
204
+ });
205
+
206
+ describe('account deletion', () => {
207
+ it('self-delete → the avatar URL is 404 at once, avatarUrl NULL, deletedAt set', async () => {
208
+ const x = await registerUser(app, 'selfdel');
209
+ const url = (await uploadAvatar(app, x.jar, await image('jpeg'))).body?.data?.avatarUrl as string;
210
+ expect((await call(app, 'GET', url)).status).toBe(200);
211
+ expect((await call(app, 'DELETE', '/users/me', { jar: x.jar, payload: { password: PASSWORD } })).status).toBe(200);
212
+ expect((await call(app, 'GET', url)).status).toBe(404);
213
+ const row = await (await db()).user.findUnique({ where: { id: x.id }, select: { avatarUrl: true, deletedAt: true } });
214
+ expect(row?.avatarUrl).toBeNull();
215
+ expect(row?.deletedAt).not.toBeNull();
216
+ });
217
+
218
+ it("an admin's delete → that avatar URL is 404 at once, avatarUrl NULL", async () => {
219
+ const y = await registerUser(app, 'admindel');
220
+ const url = (await uploadAvatar(app, y.jar, await image('png'))).body?.data?.avatarUrl as string;
221
+ expect((await call(app, 'DELETE', `/users/${y.id}`, { jar: admin.jar })).status).toBe(200);
222
+ expect((await call(app, 'GET', url)).status).toBe(404);
223
+ expect(await avatarUrlOf(y.id)).toBeNull();
224
+ });
225
+
226
+ it('the purge (31 days later) removes both upload tiers, then the row', async () => {
227
+ const x = await registerUser(app, 'purge');
228
+ await call(app, 'DELETE', '/users/me', { jar: x.jar, payload: { password: PASSWORD } });
229
+ const privateDir = path.join(integrationServices.uploadPrivateDir, 'users', x.id);
230
+ fs.mkdirSync(privateDir, { recursive: true });
231
+ fs.writeFileSync(path.join(privateDir, 'doc.txt'), 'private');
232
+ fs.mkdirSync(avatarDir(x.id), { recursive: true });
233
+ fs.writeFileSync(path.join(avatarDir(x.id), 'leftover.webp'), 'x'); // a stray public file the purge must also remove
234
+ await (await db()).user.update({ where: { id: x.id }, data: { deletedAt: new Date(Date.now() - 31 * 86_400_000) } });
235
+
236
+ const { purgeDeletedAccounts } = await import('@jobs/cleanup-deleted-accounts.job.js');
237
+ const result = await purgeDeletedAccounts();
238
+ expect(result.failed).toBe(0);
239
+ expect(await (await db()).user.count({ where: { id: x.id } })).toBe(0);
240
+ expect(fs.existsSync(privateDir)).toBe(false);
241
+ expect(fs.existsSync(path.join(integrationServices.uploadPublicDir, 'users', x.id))).toBe(false);
242
+ });
243
+ });
244
+
245
+ describe('password changes', () => {
246
+ it('your own change keeps this device (me and refresh 200) and ends the other one; 1 session left', async () => {
247
+ const z = await registerUser(app, 'ownpw');
248
+ const deviceB = await signIn(app, z.email);
249
+ const change = await call(app, 'PATCH', '/users/me/password', {
250
+ jar: z.jar,
251
+ payload: { currentPassword: PASSWORD, newPassword: 'New-Passw0rd-456!' },
252
+ });
253
+ expect(change.status).toBe(200);
254
+ expect((await call(app, 'GET', '/auth/me', { jar: z.jar })).status).toBe(200);
255
+ expect((await call(app, 'POST', '/auth/refresh', { jar: z.jar })).status).toBe(200);
256
+ const bMe = await call(app, 'GET', '/auth/me', { cookie: deviceB.header() });
257
+ expect([bMe.status, bMe.code]).toEqual([401, 'SESSION_EXPIRED']);
258
+ expect((await call(app, 'POST', '/auth/refresh', { cookie: deviceB.header() })).status).toBe(401);
259
+ expect(await (await db()).session.count({ where: { userId: z.id } })).toBe(1);
260
+ });
261
+
262
+ it("an admin's forced change ends both of that user's devices", async () => {
263
+ const w = await registerUser(app, 'forcedpw');
264
+ const wB = await signIn(app, w.email);
265
+ const forced = await call(app, 'PATCH', `/users/${w.id}/password`, { jar: admin.jar, payload: { newPassword: 'Forced-Passw0rd-789!' } });
266
+ expect(forced.status).toBe(200);
267
+ expect((await call(app, 'GET', '/auth/me', { cookie: w.jar.header() })).status).toBe(401);
268
+ expect((await call(app, 'GET', '/auth/me', { cookie: wB.header() })).status).toBe(401);
269
+ });
270
+ });
271
+
272
+ describe('who may change a user', () => {
273
+ it('another user → 403 (profile and avatar); an admin → 200; anonymous → 401', async () => {
274
+ const a = await registerUser(app, 'owner');
275
+ const b = await registerUser(app, 'stranger');
276
+ expect((await call(app, 'PATCH', `/users/${a.id}`, { jar: b.jar, payload: { firstName: 'Hacker' } })).status).toBe(403);
277
+ const byAdmin = await call(app, 'PATCH', `/users/${a.id}`, { jar: admin.jar, payload: { firstName: 'Fixed' } });
278
+ expect([byAdmin.status, byAdmin.body?.data?.firstName]).toEqual([200, 'Fixed']);
279
+ expect((await uploadAvatar(app, b.jar, await image('png'), { url: `/users/${a.id}/avatar` })).status).toBe(403);
280
+ expect((await call(app, 'PATCH', `/users/${a.id}`, { payload: { firstName: 'Anon' } })).status).toBe(401);
281
+ });
282
+
283
+ it("a private file: the owner 200 with its bytes, anonymous 401, another user 404, a traversal 404", async () => {
284
+ const owner = await registerUser(app, 'privowner');
285
+ const other = await registerUser(app, 'privother');
286
+ const dir = path.join(integrationServices.uploadPrivateDir, 'users', owner.id);
287
+ fs.mkdirSync(dir, { recursive: true });
288
+ fs.writeFileSync(path.join(dir, 'note.txt'), 'owner only');
289
+ const own = await call(app, 'GET', '/files/note.txt', { jar: owner.jar });
290
+ expect([own.status, own.res.body]).toEqual([200, 'owner only']);
291
+ expect((await call(app, 'GET', '/files/note.txt')).status).toBe(401);
292
+ expect((await call(app, 'GET', '/files/note.txt', { jar: other.jar })).status).toBe(404);
293
+ expect((await call(app, 'GET', '/files/..%2F..%2Fpublic%2Fx', { jar: owner.jar })).status).toBe(404);
294
+ });
295
+ });
@@ -0,0 +1,37 @@
1
+ /**
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.
5
+ */
6
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
7
+ import { prisma } from '@libs/prisma.js';
8
+ import { usersRepository } from '../users.repo.js';
9
+
10
+ vi.mock('@libs/prisma.js', () => ({
11
+ prisma: { user: { update: vi.fn(), updateMany: vi.fn() } },
12
+ }));
13
+
14
+ beforeEach(() => {
15
+ vi.clearAllMocks();
16
+ });
17
+
18
+ describe('usersRepository', () => {
19
+ it('softDeleteUser clears the avatar URL with the deletion', async () => {
20
+ await usersRepository.softDeleteUser('u1');
21
+ expect(prisma.user.update).toHaveBeenCalledWith({
22
+ where: { id: 'u1' },
23
+ data: { deletedAt: expect.any(Date), isActive: false, avatarUrl: null },
24
+ });
25
+ });
26
+
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' },
34
+ });
35
+ expect(vi.mocked(prisma.user.updateMany).mock.calls[1]?.[0]?.where).toMatchObject({ avatarUrl: null });
36
+ });
37
+ });
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Password confirmation in users.service: a wrong password is wrong INPUT
3
+ * (422 with its own code), never 401. A 401 tells the client "your session
4
+ * expired", which made it run a pointless token refresh.
5
+ */
6
+ import { describe, expect, it, vi, beforeEach } from 'vitest';
7
+ import { usersService } from '../users.service.js';
8
+ import * as authRepo from '@modules/auth/auth.repo.js';
9
+ import { sessionRepository } from '@modules/auth/session.repo.js';
10
+ import { usersRepository } from '../users.repo.js';
11
+ import { hashPassword, verifyPassword } from '@libs/password.js';
12
+ import { fileStorageService } from '@libs/storage/file-storage.service.js';
13
+ import { testUsers } from '@/test/setup.js';
14
+
15
+ vi.mock('@modules/auth/auth.repo.js');
16
+ vi.mock('@modules/auth/session.repo.js');
17
+ vi.mock('../users.repo.js');
18
+ vi.mock('@libs/password.js');
19
+ vi.mock('@libs/storage/file-storage.service.js', () => ({ fileStorageService: { deleteAvatar: vi.fn() } }));
20
+ vi.mock('@libs/storage/image-optimizer.service.js', () => ({ imageOptimizerService: {} }));
21
+
22
+ const user = testUsers.validUser;
23
+
24
+ describe('users.service password confirmation', () => {
25
+ beforeEach(() => {
26
+ vi.clearAllMocks();
27
+ vi.mocked(authRepo.findUserById).mockResolvedValue(user);
28
+ vi.mocked(hashPassword).mockResolvedValue('new-hash');
29
+ });
30
+
31
+ it('changePassword with a wrong current password answers 422 INVALID_CURRENT_PASSWORD and changes nothing', async () => {
32
+ vi.mocked(verifyPassword).mockResolvedValue(false);
33
+ await expect(
34
+ usersService.changePassword(user.id, { currentPassword: 'wrong', newPassword: 'New-Passw0rd-123!' }),
35
+ ).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();
38
+ });
39
+
40
+ it('changePassword with the right current password still changes it and ends all sessions', async () => {
41
+ // First call: current password matches; second: the new one differs from it.
42
+ 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);
46
+ });
47
+
48
+ it('deleteAccount with a wrong password answers 422 INVALID_PASSWORD and deletes nothing', async () => {
49
+ vi.mocked(verifyPassword).mockResolvedValue(false);
50
+ await expect(usersService.deleteAccount(user.id, 'wrong')).rejects.toMatchObject({
51
+ statusCode: 422,
52
+ code: 'INVALID_PASSWORD',
53
+ message: 'Incorrect password',
54
+ });
55
+ expect(usersRepository.softDeleteUser).not.toHaveBeenCalled();
56
+ });
57
+
58
+ it('deleteAccount with the right password still soft-deletes and ends all sessions', async () => {
59
+ 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);
63
+ });
64
+
65
+ it('deleteAccount removes the public avatar at once, after the soft delete', async () => {
66
+ vi.mocked(verifyPassword).mockResolvedValue(true);
67
+ await usersService.deleteAccount(user.id, 'right');
68
+ expect(fileStorageService.deleteAvatar).toHaveBeenCalledWith(user.id);
69
+ const softDeletedAt = vi.mocked(usersRepository.softDeleteUser).mock.invocationCallOrder[0];
70
+ expect(vi.mocked(fileStorageService.deleteAvatar).mock.invocationCallOrder[0]).toBeGreaterThan(softDeletedAt);
71
+ });
72
+
73
+ 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);
83
+ });
84
+
85
+ it("an owner's password change keeps the asking device signed in and ends every other session", async () => {
86
+ 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();
91
+ });
92
+
93
+ it('an admin-forced password change still ends every session of that user', async () => {
94
+ 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();
99
+ });
100
+
101
+ it('the last active admin cannot delete their own account (409 LAST_ADMIN), and nothing is deleted', async () => {
102
+ vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
103
+ 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' });
106
+ expect(usersRepository.softDeleteUser).not.toHaveBeenCalled();
107
+ });
108
+
109
+ it('an admin can delete their own account when another active admin exists', async () => {
110
+ vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
111
+ 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);
115
+ });
116
+
117
+ it('a wrong password still answers 422 first, even for the last admin', async () => {
118
+ vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
119
+ vi.mocked(verifyPassword).mockResolvedValue(false);
120
+ await expect(usersService.deleteAccount(user.id, 'wrong')).rejects.toMatchObject({ code: 'INVALID_PASSWORD' });
121
+ expect(usersRepository.countOtherActiveAdmins).not.toHaveBeenCalled();
122
+ });
123
+
124
+ it('a normal user never triggers the admin check', async () => {
125
+ vi.mocked(verifyPassword).mockResolvedValue(true);
126
+ await usersService.deleteAccount(user.id, 'right');
127
+ expect(usersRepository.countOtherActiveAdmins).not.toHaveBeenCalled();
128
+ });
129
+ });