create-tigra 4.1.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -1
  3. package/bin/create-tigra.js +68 -73
  4. package/lib/installer-transaction.js +275 -0
  5. package/lib/patchers/diagnostics.patcher.js +33 -59
  6. package/lib/patchers/email-verification.patcher.js +86 -92
  7. package/lib/patchers/metrics.patcher.js +18 -18
  8. package/lib/project-files.js +99 -0
  9. package/modules/diagnostics/diagnostics.md +10 -0
  10. package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
  11. package/modules/diagnostics/prisma/migration.sql +1 -24
  12. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
  13. package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
  14. package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
  15. package/modules/email-verification/client/hooks/useVerification.ts +4 -7
  16. package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
  17. package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
  18. package/modules/email-verification/server/verification.service.ts +102 -157
  19. package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
  20. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
  21. package/modules/metrics/performance.md +2 -2
  22. package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
  23. package/modules/metrics/server/metrics.collector.ts +6 -3
  24. package/modules/metrics/server/metrics.routes.ts +1 -2
  25. package/modules/metrics/server/metrics.service.ts +6 -2
  26. package/package.json +1 -1
  27. package/template/AGENTS.md +4 -3
  28. package/template/client/.dockerignore +2 -5
  29. package/template/client/gitignore +43 -0
  30. package/template/client/package-lock.json +51 -51
  31. package/template/client/package.json +2 -2
  32. package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
  33. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  34. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  35. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  36. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  37. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  38. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  39. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  40. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  41. package/template/client/src/lib/api/axios.config.ts +24 -6
  42. package/template/client/src/lib/api/session-events.ts +54 -0
  43. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  44. package/template/client/src/store/__tests__/store.test.ts +1 -0
  45. package/template/gitignore +3 -2
  46. package/template/server/.dockerignore +2 -5
  47. package/template/server/.env.example +1 -0
  48. package/template/server/.env.example.production +1 -0
  49. package/template/server/README.md +7 -2
  50. package/template/server/docs/deployment.md +66 -0
  51. package/template/server/docs/logging.md +9 -8
  52. package/template/server/docs/rate-limits.md +6 -4
  53. package/template/server/gitignore +33 -0
  54. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  55. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  56. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  57. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  58. package/template/server/prisma/schema.prisma +25 -1
  59. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  60. package/template/server/src/app.ts +14 -5
  61. package/template/server/src/config/env.ts +8 -0
  62. package/template/server/src/config/rate-limit.config.ts +1 -1
  63. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  64. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  65. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  66. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  67. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  68. package/template/server/src/jobs/index.ts +8 -2
  69. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  70. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  71. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  72. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  73. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  74. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  75. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  76. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  77. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  78. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  79. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  80. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  81. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  82. package/template/server/src/libs/account-mutation.ts +77 -0
  83. package/template/server/src/libs/auth.ts +37 -3
  84. package/template/server/src/libs/cookies.ts +25 -13
  85. package/template/server/src/libs/email-quota.ts +11 -7
  86. package/template/server/src/libs/email.ts +11 -8
  87. package/template/server/src/libs/error-handler.ts +16 -12
  88. package/template/server/src/libs/http.ts +37 -13
  89. package/template/server/src/libs/ip-block.ts +56 -34
  90. package/template/server/src/libs/logger.ts +23 -8
  91. package/template/server/src/libs/monitoring.ts +57 -31
  92. package/template/server/src/libs/observability/sentry.ts +65 -49
  93. package/template/server/src/libs/prisma.ts +1 -1
  94. package/template/server/src/libs/private-cache.ts +6 -0
  95. package/template/server/src/libs/rate-limiting.ts +4 -0
  96. package/template/server/src/libs/requestLogger.ts +3 -3
  97. package/template/server/src/libs/safe-http.ts +58 -18
  98. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  99. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  100. package/template/server/src/libs/storage/file-validator.ts +2 -1
  101. package/template/server/src/libs/url-safety.ts +10 -2
  102. package/template/server/src/libs/validation-errors.ts +11 -8
  103. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  104. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  105. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  106. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  107. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  108. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  109. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  110. package/template/server/src/modules/admin/admin.service.ts +61 -62
  111. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  112. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  113. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  114. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  115. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  116. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  117. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  118. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  119. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  120. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  121. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  122. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  123. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  124. package/template/server/src/modules/auth/auth.service.ts +33 -237
  125. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  126. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  127. package/template/server/src/modules/auth/session.repo.ts +5 -4
  128. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  129. package/template/server/src/modules/files/files.controller.ts +2 -2
  130. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  131. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  132. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  133. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  134. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  135. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  136. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  137. package/template/server/src/modules/users/users.controller.ts +28 -25
  138. package/template/server/src/modules/users/users.repo.ts +12 -51
  139. package/template/server/src/modules/users/users.service.ts +109 -234
  140. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  141. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  142. package/template/server/src/test/setup.ts +4 -0
@@ -0,0 +1,13 @@
1
+ -- CreateTable
2
+ CREATE TABLE `retired_refresh_tokens` (
3
+ `fingerprint` CHAR(64) NOT NULL,
4
+ `sessionId` VARCHAR(191) NOT NULL,
5
+ `expiresAt` DATETIME(3) NOT NULL,
6
+
7
+ INDEX `retired_refresh_tokens_sessionId_idx`(`sessionId`),
8
+ INDEX `retired_refresh_tokens_expiresAt_idx`(`expiresAt`),
9
+ PRIMARY KEY (`fingerprint`)
10
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
11
+
12
+ -- AddForeignKey
13
+ ALTER TABLE `retired_refresh_tokens` ADD CONSTRAINT `retired_refresh_tokens_sessionId_fkey` FOREIGN KEY (`sessionId`) REFERENCES `sessions`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,9 @@
1
+ -- CreateTable
2
+ CREATE TABLE `avatar_cleanup` (
3
+ `userId` VARCHAR(191) NOT NULL,
4
+ `filename` VARCHAR(191) NOT NULL,
5
+ `dueAt` DATETIME(3) NOT NULL,
6
+
7
+ INDEX `avatar_cleanup_dueAt_idx`(`dueAt`),
8
+ PRIMARY KEY (`userId`, `filename`)
9
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -0,0 +1 @@
1
+ ALTER TABLE `users` ADD COLUMN `purgeStartedAt` DATETIME(3) NULL;
@@ -29,7 +29,9 @@ model User {
29
29
  // REQUIRE_USER_VERIFICATION is on.
30
30
  emailVerifiedAt DateTime?
31
31
  deletedAt DateTime?
32
-
32
+ // Set before deleting media. A claimed account can no longer be restored,
33
+ // and stays discoverable for retries until the permanent delete commits.
34
+ purgeStartedAt DateTime?
33
35
 
34
36
  createdAt DateTime @default(now())
35
37
  updatedAt DateTime @updatedAt
@@ -80,6 +82,7 @@ model Session {
80
82
 
81
83
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
82
84
  refreshTokens RefreshToken[]
85
+ retiredRefreshTokens RetiredRefreshToken[]
83
86
 
84
87
  // Performance indexes for session queries
85
88
  @@index([userId])
@@ -88,6 +91,27 @@ model Session {
88
91
  @@map("sessions")
89
92
  }
90
93
 
94
+ model RetiredRefreshToken {
95
+ fingerprint String @id @db.Char(64)
96
+ sessionId String
97
+ expiresAt DateTime
98
+ session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
99
+
100
+ @@index([sessionId])
101
+ @@index([expiresAt])
102
+ @@map("retired_refresh_tokens")
103
+ }
104
+
105
+ model AvatarCleanup {
106
+ userId String
107
+ filename String
108
+ dueAt DateTime
109
+
110
+ @@id([userId, filename])
111
+ @@index([dueAt])
112
+ @@map("avatar_cleanup")
113
+ }
114
+
91
115
  model BlockedIp {
92
116
  id String @id @default(uuid())
93
117
  ip String @unique @db.VarChar(45)
@@ -162,7 +162,9 @@ describe('auth routes answer', () => {
162
162
  const reg = await call(app, 'POST', '/auth/register', { payload: { email, password: PASSWORD, firstName: 'Con', lastName: 'Tract' } });
163
163
  expect([reg.status, reg.body?.data?.user?.email]).toEqual([201, email]);
164
164
  const jar = await signIn(app, email);
165
- expect((await call(app, 'GET', '/auth/me', { jar })).body?.data?.email).toBe(email);
165
+ const me = await call(app, 'GET', '/auth/me', { jar });
166
+ expect(me.body?.data?.email).toBe(email);
167
+ expect(me.res.headers['cache-control']).toBe('private, no-store');
166
168
  const sessions = await call(app, 'GET', '/auth/sessions', { jar });
167
169
  expect([sessions.status, Array.isArray(sessions.body?.data) && sessions.body?.data.length >= 1]).toEqual([200, true]);
168
170
  expect((await call(app, 'POST', '/auth/refresh', { jar })).status).toBe(200);
@@ -180,7 +182,7 @@ describe('auth routes answer', () => {
180
182
  const u = await registerUser(app, 'contract-reset');
181
183
  expect((await call(app, 'POST', '/auth/forgot-password', { payload: { email: u.email } })).status).toBe(200);
182
184
  expect((await call(app, 'POST', '/auth/forgot-password', { payload: { email: uniqueEmail('nobody') } })).status).toBe(200);
183
- const token = tokenOf(mail.to(u.email).at(-1)?.link ?? null);
185
+ const token = tokenOf((await mail.waitFor(u.email, (e) => /reset-password/.test(e.link ?? ''))).at(-1)?.link ?? null);
184
186
  expect((await call(app, 'POST', '/auth/reset-password', { payload: { token, newPassword: 'Reset-Passw0rd-1' } })).status).toBe(200);
185
187
  const bad = await call(app, 'POST', '/auth/reset-password', { payload: { token: 'f'.repeat(64), newPassword: 'Reset-Passw0rd-1' } });
186
188
  expect([bad.status, bad.code]).toEqual([400, 'INVALID_RESET_TOKEN']);
@@ -228,6 +230,7 @@ describe('admin routes answer', () => {
228
230
  it('stats, health, client-ip and blocked-ips lists → 200 with their shapes', async () => {
229
231
  const stats = await call(app, 'GET', '/admin/stats', { jar: admin.jar });
230
232
  expect(stats.status).toBe(200);
233
+ expect(stats.res.headers['cache-control']).toBe('private, no-store');
231
234
  expect(stats.body?.data).toEqual(expect.objectContaining({ totalUsers: expect.any(Number) }));
232
235
  expect((await call(app, 'GET', '/admin/health', { jar: admin.jar })).status).toBe(200);
233
236
  expect(Object.keys((await call(app, 'GET', '/admin/client-ip', { jar: admin.jar })).body?.data ?? {}).sort()).toEqual(['ip', 'source']);
@@ -1,4 +1,5 @@
1
1
  import Fastify, { type FastifyInstance, type FastifyRequest, type RouteOptions } from 'fastify';
2
+ import { relative, sep } from 'node:path';
2
3
  import cors from '@fastify/cors';
3
4
  import helmet from '@fastify/helmet';
4
5
  import cookie from '@fastify/cookie';
@@ -143,15 +144,23 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
143
144
  // auth-gated, owner-scoped route GET /api/v1/files/:filename (filesRoutes).
144
145
  // Serving UPLOAD_PUBLIC_DIR at prefix '/uploads/' puts avatars at
145
146
  // /uploads/users/{id}/avatar/avatar-<hex>.webp.
146
- // Cached for a year, immutable: a public file never changes under its name
147
- // (every new avatar gets a new random name, see file-storage.service.ts), so
148
- // browsers and CDNs never need to re-check it. Anything else written to the
149
- // public tier must follow the same rule.
147
+ // Other public assets use immutable names. Avatars are user-removable, so
148
+ // browsers and CDNs must fetch them again each time they are requested.
149
+ const publicUploadDir = fileStorageService.getPublicDir();
150
150
  await app.register(fastifyStatic, {
151
- root: fileStorageService.getPublicDir(),
151
+ root: publicUploadDir,
152
152
  prefix: '/uploads/',
153
+ dotfiles: 'ignore', // Partially written avatar files stay behind a dot filename.
153
154
  maxAge: 365 * 24 * 60 * 60 * 1000, // ms
154
155
  immutable: true,
156
+ setHeaders(reply, servedPath): void {
157
+ // Match the directory so legacy filenames use the same policy. Windows
158
+ // can serve alternate casing for the same on-disk directory.
159
+ const parts = relative(publicUploadDir, servedPath).split(sep);
160
+ if (parts.length === 4 && parts[0]?.toLowerCase() === 'users' && parts[2]?.toLowerCase() === 'avatar') {
161
+ reply.header('Cache-Control', 'no-store');
162
+ }
163
+ },
155
164
  });
156
165
 
157
166
  // --- Sync permanent IP blocks from DB to Redis ---
@@ -147,6 +147,14 @@ const envSchema = z.object({
147
147
  // Applies only to the non-secret auth_session cookie; the token cookies are
148
148
  // always host-only on the API (see src/libs/cookies.ts).
149
149
  COOKIE_DOMAIN: optionalEnv(z.string().optional()),
150
+ COOKIE_LEGACY_DOMAINS: optionalEnv(z.string().optional())
151
+ .transform(value => [...new Set((value ?? '').split(',').map(domain =>
152
+ domain.trim().toLowerCase().replace(/^\./, ''),
153
+ ).filter(Boolean))])
154
+ .refine(domains => domains.every(domain =>
155
+ domain.length <= 253 && /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(domain)
156
+ && !/^\d+(?:\.\d+)+$/.test(domain),
157
+ ), 'Expected a comma-separated list of cookie domain names'),
150
158
 
151
159
  // --- Account Activation ---
152
160
  // When true, new users start with emailVerifiedAt = null and cannot sign in
@@ -165,7 +165,7 @@ export const RATE_LIMITS = {
165
165
  // Files — auth-gated private file streaming
166
166
  FILES_GET: routeLimit('FILES_GET', 100, '1m'),
167
167
 
168
- // Admin routes
168
+ // Admin routes use this quota until the request is authorized as staff.
169
169
  ADMIN_DEFAULT: routeLimit('ADMIN_DEFAULT', 30, '1m'),
170
170
  } as const;
171
171
 
@@ -11,8 +11,7 @@ import { purgeDeletedAccounts, startCleanupDeletedAccountsJob } from '../cleanup
11
11
  // database and is retried by the next run.
12
12
 
13
13
  vi.mock('@libs/prisma.js', () => ({
14
- prisma: { user: { findMany: vi.fn(), delete: vi.fn() } },
15
- isPrismaNotFound: (e: unknown): boolean => (e as { code?: string })?.code === 'P2025',
14
+ prisma: { user: { findMany: vi.fn(), delete: vi.fn(), updateMany: vi.fn() }, $transaction: vi.fn() },
16
15
  }));
17
16
  vi.mock('@libs/storage/file-storage.service.js', () => ({
18
17
  fileStorageService: { deleteUserMedia: vi.fn() },
@@ -22,8 +21,13 @@ vi.mock('@libs/logger.js', () => ({
22
21
  }));
23
22
 
24
23
  describe('purgeDeletedAccounts', () => {
24
+ const lock = vi.fn();
25
25
  beforeEach(() => {
26
- vi.clearAllMocks();
26
+ vi.resetAllMocks();
27
+ vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 1 });
28
+ lock.mockResolvedValue([{ id: 'selected' }]);
29
+ vi.mocked(prisma.$transaction).mockImplementation((async (work: (tx: unknown) => Promise<unknown>) =>
30
+ work({ user: { delete: prisma.user.delete }, $queryRaw: lock })) as never);
27
31
  });
28
32
 
29
33
  it('only selects accounts soft-deleted more than 30 days ago', async () => {
@@ -33,12 +37,23 @@ describe('purgeDeletedAccounts', () => {
33
37
  const result = await purgeDeletedAccounts(now);
34
38
 
35
39
  const where = vi.mocked(prisma.user.findMany).mock.calls[0][0]?.where as {
36
- deletedAt: { not: null; lt: Date };
40
+ OR: [{ deletedAt: { lt: Date } }];
37
41
  };
38
- expect(where.deletedAt.lt.toISOString()).toBe('2026-03-01T12:00:00.000Z');
42
+ expect(where.OR[0].deletedAt.lt.toISOString()).toBe('2026-03-01T12:00:00.000Z');
39
43
  expect(result).toEqual({ found: 0, purged: 0, failed: 0 });
40
44
  });
41
45
 
46
+ it('does not touch media when a selected account is no longer pending purge', async () => {
47
+ vi.mocked(prisma.user.findMany).mockResolvedValue([{ id: 'restored' }] as never);
48
+ vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 0 });
49
+ lock.mockResolvedValue([]);
50
+
51
+ const result = await purgeDeletedAccounts();
52
+
53
+ expect(fileStorageService.deleteUserMedia).not.toHaveBeenCalled();
54
+ expect(result).toEqual({ found: 1, purged: 0, failed: 0 });
55
+ });
56
+
42
57
  it('keeps going when one account fails and reports the counts', async () => {
43
58
  vi.mocked(prisma.user.findMany).mockResolvedValue([{ id: 'a' }, { id: 'b' }, { id: 'c' }] as never);
44
59
  vi.mocked(prisma.user.delete).mockImplementation((({ where }: { where: { id: string } }) =>
@@ -50,14 +65,16 @@ describe('purgeDeletedAccounts', () => {
50
65
  expect(prisma.user.delete).toHaveBeenCalledTimes(3);
51
66
  });
52
67
 
53
- it('removes the files before the row', async () => {
68
+ it('claims the account before files and removes the files before the row', async () => {
54
69
  vi.mocked(prisma.user.findMany).mockResolvedValue([{ id: 'a' }] as never);
55
70
  vi.mocked(prisma.user.delete).mockResolvedValue({} as never);
56
71
 
57
72
  await purgeDeletedAccounts();
58
73
 
59
74
  const filesAt = vi.mocked(fileStorageService.deleteUserMedia).mock.invocationCallOrder[0];
75
+ const claimAt = vi.mocked(prisma.user.updateMany).mock.invocationCallOrder[0];
60
76
  const rowAt = vi.mocked(prisma.user.delete).mock.invocationCallOrder[0];
77
+ expect(claimAt).toBeLessThan(filesAt);
61
78
  expect(filesAt).toBeLessThan(rowAt);
62
79
  });
63
80
 
@@ -73,12 +90,12 @@ describe('purgeDeletedAccounts', () => {
73
90
  expect(prisma.user.delete).not.toHaveBeenCalledWith({ where: { id: 'a' } });
74
91
  });
75
92
 
76
- it('an account another process purged a moment ago counts as purged, without an error log', async () => {
93
+ it('leaves a row owned by another worker alone without an error log', async () => {
77
94
  vi.mocked(prisma.user.findMany).mockResolvedValue([{ id: 'z' }] as never);
78
95
  vi.mocked(fileStorageService.deleteUserMedia).mockResolvedValue(undefined);
79
- vi.mocked(prisma.user.delete).mockRejectedValue(Object.assign(new Error('not found'), { code: 'P2025' }));
96
+ lock.mockResolvedValue([]);
80
97
 
81
- await expect(purgeDeletedAccounts()).resolves.toEqual({ found: 1, purged: 1, failed: 0 });
98
+ await expect(purgeDeletedAccounts()).resolves.toEqual({ found: 1, purged: 0, failed: 0 });
82
99
  expect(logger.error).not.toHaveBeenCalled();
83
100
  });
84
101
 
@@ -10,7 +10,7 @@ import { pruneExpiredAutoBlocks } from '@libs/ip-block.js';
10
10
  import { cleanupExpiredAuth, startCleanupExpiredAuthJob } from '../cleanup-expired-auth.job.js';
11
11
 
12
12
  vi.mock('@libs/prisma.js', () => ({
13
- prisma: { refreshToken: { deleteMany: vi.fn() }, session: { deleteMany: vi.fn() } },
13
+ prisma: { refreshToken: { deleteMany: vi.fn() }, retiredRefreshToken: { deleteMany: vi.fn() }, session: { deleteMany: vi.fn() } },
14
14
  }));
15
15
  vi.mock('@libs/ip-block.js', () => ({ pruneExpiredAutoBlocks: vi.fn() }));
16
16
  vi.mock('@libs/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
@@ -27,6 +27,7 @@ describe('cleanupExpiredAuth', () => {
27
27
  const now = new Date('2026-10-19T12:00:00Z');
28
28
  await expect(cleanupExpiredAuth(now)).resolves.toEqual({ tokens: 3, sessions: 2, autoBlocks: 4 });
29
29
  expect(prisma.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { expiresAt: { lt: now } } });
30
+ expect(prisma.retiredRefreshToken.deleteMany).toHaveBeenCalledWith({ where: { expiresAt: { lte: now } } });
30
31
  expect(prisma.session.deleteMany).toHaveBeenCalledWith({ where: { expiresAt: { lt: now } } });
31
32
  expect(pruneExpiredAutoBlocks).toHaveBeenCalledWith(now.getTime() / 1000);
32
33
  });
@@ -8,9 +8,9 @@
8
8
  * - The auth cleanup removes expired sessions and refresh tokens, keeps live
9
9
  * ones, and prunes expired automatic IP blocks while keeping running ones.
10
10
  */
11
- import { afterAll, beforeAll, describe, expect, it } from 'vitest';
11
+ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
12
12
  import type { FastifyInstance } from 'fastify';
13
- import { PASSWORD, buildTestApp, call, db, redis, registerUser, signIn } from '@/test/integration-helpers.js';
13
+ import { PASSWORD, buildTestApp, call, db, redis, registerAdmin, registerUser, signIn } from '@/test/integration-helpers.js';
14
14
 
15
15
  let app: FastifyInstance;
16
16
 
@@ -47,15 +47,58 @@ describe('purge of deleted accounts', () => {
47
47
 
48
48
  it('two purges at once (two server processes) both finish without a failure; every account is gone', async () => {
49
49
  // Several accounts, so the two runs work on the same rows at the same time.
50
- // Here both usually read a row before either deletes it, and the second
51
- // DELETE simply removes nothing. The other order (the row is gone before
52
- // the read, Prisma P2025) is pinned by cleanup-deleted-accounts.job.test.ts.
50
+ // A contender may skip a lock owned by the other worker. In total there
51
+ // must be one committed delete per account.
53
52
  const ids = await Promise.all([0, 1, 2, 3, 4, 5].map((i) => deletedAccount(`purge-race-${i}`, 40)));
54
53
  const { purgeDeletedAccounts } = await import('@jobs/cleanup-deleted-accounts.job.js');
55
54
  const results = await Promise.all([purgeDeletedAccounts(), purgeDeletedAccounts()]);
56
55
  expect(results.map((r) => r.failed)).toEqual([0, 0]);
56
+ expect(results.reduce((count, run) => count + run.purged, 0)).toBe(ids.length);
57
57
  expect(await (await db()).user.count({ where: { id: { in: ids } } })).toBe(0);
58
58
  });
59
+
60
+ it('leaves a durable claim after a media error, rejects restore over HTTP, then retries', async () => {
61
+ const id = await deletedAccount('purge-media-retry', 31);
62
+ const admin = await registerAdmin(app, 'purge-media-admin');
63
+ const prisma = await db();
64
+ const { fileStorageService } = await import('@libs/storage/file-storage.service.js');
65
+ const { purgeDeletedAccounts } = await import('@jobs/cleanup-deleted-accounts.job.js');
66
+ const failure = vi.spyOn(fileStorageService, 'deleteUserMedia').mockRejectedValueOnce(new Error('fixture storage failure'));
67
+ try {
68
+ const result = await purgeDeletedAccounts();
69
+ expect(result).toEqual({ found: 1, purged: 0, failed: 1 });
70
+ const claimed = await prisma.user.findUniqueOrThrow({ where: { id } });
71
+ expect(claimed.purgeStartedAt).toBeInstanceOf(Date);
72
+ } finally {
73
+ failure.mockRestore();
74
+ }
75
+
76
+ const origin = await app.listen({ host: '127.0.0.1', port: 0 });
77
+ const restore = await fetch(`${origin}/api/v1/admin/users/${id}/restore`, {
78
+ method: 'POST',
79
+ headers: { cookie: admin.jar.header() },
80
+ });
81
+ expect(restore.status).toBe(409);
82
+ expect(await restore.json()).toMatchObject({ error: { code: 'USER_PURGE_IN_PROGRESS' } });
83
+
84
+ // An earlier clock on a replacement worker cannot defer a committed claim.
85
+ expect(await purgeDeletedAccounts(new Date(0))).toEqual({ found: 1, purged: 1, failed: 0 });
86
+ expect(await prisma.user.count({ where: { id } })).toBe(0);
87
+ });
88
+
89
+ it('retains records at and after the UTC cutoff and purges only an older one', async () => {
90
+ const prisma = await db();
91
+ const now = new Date('2026-03-31T12:00:00.000Z');
92
+ const boundary = now.getTime() - 30 * DAY_MS;
93
+ const ids = await Promise.all(['before', 'at', 'after'].map((tag) => deletedAccount(`cutoff-${tag}`, 0)));
94
+ for (const [i, id] of ids.entries()) {
95
+ await prisma.user.update({ where: { id }, data: { deletedAt: new Date(boundary + i - 1) } });
96
+ }
97
+ const { purgeDeletedAccounts } = await import('@jobs/cleanup-deleted-accounts.job.js');
98
+ expect(await purgeDeletedAccounts(now)).toEqual({ found: 1, purged: 1, failed: 0 });
99
+ expect(await prisma.user.count({ where: { id: ids[0] } })).toBe(0);
100
+ expect(await prisma.user.count({ where: { id: { in: ids.slice(1) } } })).toBe(2);
101
+ });
59
102
  });
60
103
 
61
104
  describe('cleanup of expired auth records', () => {
@@ -69,6 +112,9 @@ describe('cleanup of expired auth records', () => {
69
112
  await prisma.refreshToken.updateMany({ where: { sessionId: expired.id }, data: { expiresAt: past } });
70
113
 
71
114
  const { cleanupExpiredAuth } = await import('@jobs/cleanup-expired-auth.job.js');
115
+ const stale = u.jar.copy();
116
+ expect((await call(app, 'GET', '/auth/me', { jar: stale })).status).toBe(401);
117
+ expect((await call(app, 'POST', '/auth/refresh', { jar: u.jar.copy() })).status).toBe(401);
72
118
  await cleanupExpiredAuth();
73
119
  expect(await prisma.session.count({ where: { id: expired.id } })).toBe(0);
74
120
  expect(await prisma.refreshToken.count({ where: { sessionId: expired.id } })).toBe(0);
@@ -2,15 +2,13 @@
2
2
  * Cleanup Deleted Accounts Job
3
3
  *
4
4
  * Permanently purges soft-deleted user accounts after a 30-day retention period.
5
- * Deletes all of the user's media from disk first (public AND private tier),
6
- * then hard-deletes the user record (cascades to refresh tokens and sessions;
5
+ * Claims the account before deleting its media (public AND private tier), then
6
+ * hard-deletes the user record (cascades to refresh tokens and sessions;
7
7
  * IP blocks the user created as an admin are kept, with blockedBy set to NULL).
8
8
  *
9
- * Files first, row last: while the row exists, the account is found again by
10
- * the next run, so a failed file deletion is simply retried. The old order
11
- * (row first) left files no run could ever find again, a public avatar
12
- * included. (The public avatar is normally gone already: deleting the account
13
- * removes it at once, see usersService.deleteAccount.)
9
+ * The claim and restore compete on the same row. After a claim commits, a
10
+ * failed or interrupted media deletion leaves a retryable row that cannot be
11
+ * restored with missing files.
14
12
  *
15
13
  * Runs about a minute after start, then once a day (jobs/schedule.ts): a
16
14
  * deploy or restart never pushes the purge back by another day.
@@ -19,7 +17,7 @@
19
17
  */
20
18
 
21
19
  import type { FastifyInstance } from 'fastify';
22
- import { prisma, isPrismaNotFound } from '@libs/prisma.js';
20
+ import { prisma } from '@libs/prisma.js';
23
21
  import { logger } from '@libs/logger.js';
24
22
  import { fileStorageService } from '@libs/storage/file-storage.service.js';
25
23
  import { startRecurringJob } from './schedule.js';
@@ -28,6 +26,7 @@ const INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
28
26
  const FIRST_RUN_DELAY_MS = 60 * 1000;
29
27
  /** Days a soft-deleted account is kept (restorable by an admin) before the purge. */
30
28
  export const RETENTION_DAYS = 30;
29
+ export const RETENTION_MS = RETENTION_DAYS * 24 * 60 * 60 * 1000;
31
30
 
32
31
  export interface PurgeResult {
33
32
  found: number;
@@ -43,44 +42,41 @@ export interface PurgeResult {
43
42
  * is logged at error level with the user id.
44
43
  */
45
44
  export async function purgeDeletedAccounts(now: Date = new Date()): Promise<PurgeResult> {
46
- const cutoffDate = new Date(now);
47
- cutoffDate.setDate(cutoffDate.getDate() - RETENTION_DAYS);
45
+ const cutoffDate = new Date(now.getTime() - RETENTION_MS);
48
46
 
49
- // Find users soft-deleted more than 30 days ago
47
+ // Claims stay due even if the next worker starts with an earlier clock.
50
48
  const usersToDelete = await prisma.user.findMany({
51
49
  where: {
52
- deletedAt: {
53
- not: null,
54
- lt: cutoffDate,
55
- },
56
- },
57
- select: {
58
- id: true,
50
+ deletedAt: { not: null },
51
+ OR: [{ deletedAt: { lt: cutoffDate } }, { purgeStartedAt: { not: null } }],
59
52
  },
53
+ select: { id: true, purgeStartedAt: true },
60
54
  });
61
55
 
62
56
  const result: PurgeResult = { found: usersToDelete.length, purged: 0, failed: 0 };
63
57
 
64
58
  for (const user of usersToDelete) {
65
59
  try {
66
- // Media first (no-op if the folders don't exist). If it throws, the row
67
- // stays and the next run retries this account.
68
- await fileStorageService.deleteUserMedia(user.id);
69
-
70
- // Then the row (cascades to RefreshToken + Session). If only this fails,
71
- // the next run finds the account again; its media is already gone.
72
- try {
73
- await prisma.user.delete({
74
- where: { id: user.id },
60
+ if (!user.purgeStartedAt) {
61
+ await prisma.user.updateMany({
62
+ where: { id: user.id, deletedAt: { lt: cutoffDate }, purgeStartedAt: null },
63
+ data: { purgeStartedAt: now },
75
64
  });
76
- } catch (error) {
77
- // Another server process (a replica, or the old container during a
78
- // deploy) purged it a moment ago: the account is gone, which is the
79
- // goal. Not a failure, so no error log.
80
- if (!isPrismaNotFound(error)) throw error;
81
65
  }
82
-
83
- result.purged++;
66
+ const purged = await prisma.$transaction(async (tx) => {
67
+ // A row lock prevents simultaneous workers from touching its media.
68
+ // Skipped rows stay eligible for retry without blocking other purges.
69
+ const rows = await tx.$queryRaw<{ id: string }[]>`
70
+ SELECT id FROM users WHERE id = ${user.id}
71
+ AND deletedAt IS NOT NULL AND purgeStartedAt IS NOT NULL
72
+ FOR UPDATE SKIP LOCKED
73
+ `;
74
+ if (!rows.length) return false;
75
+ await fileStorageService.deleteUserMedia(user.id);
76
+ await tx.user.delete({ where: { id: user.id } });
77
+ return true;
78
+ }, { timeout: 30_000 });
79
+ if (purged) result.purged++;
84
80
  } catch (error) {
85
81
  result.failed++;
86
82
  logger.error({ err: error, userId: user.id }, 'Failed to purge deleted account');
@@ -22,6 +22,8 @@ export async function cleanupExpiredAuth(
22
22
  const deletedTokens = await prisma.refreshToken.deleteMany({
23
23
  where: { expiresAt: { lt: now } },
24
24
  });
25
+ // Request paths enforce the short deadline even between cleanup passes.
26
+ await prisma.retiredRefreshToken.deleteMany({ where: { expiresAt: { lte: now } } });
25
27
 
26
28
  const deletedSessions = await prisma.session.deleteMany({
27
29
  where: { expiresAt: { lt: now } },
@@ -4,19 +4,23 @@
4
4
  * Registers all background jobs with the Fastify instance. They run inside the
5
5
  * server process, each once shortly after start and then on its interval
6
6
  * (jobs/schedule.ts), so a deploy never postpones them. With several server
7
- * processes (replicas) each runs them too; that is safe, the jobs are
8
- * idempotent (the purge treats an account another process removed as done).
7
+ * processes (replicas) each runs them too. The purge locks its claimed user
8
+ * row while removing media, and the periodic expiry deletions are idempotent.
9
9
  *
10
10
  * - cleanup-expired-auth: hourly, expired refresh tokens and sessions, and
11
11
  * expired automatic IP blocks in Redis
12
12
  * - purge-deleted-accounts: daily, accounts deleted more than 30 days ago
13
13
  * - refresh-cloudflare-ranges: daily, Cloudflare's edge IP ranges (not in tests)
14
+ * - password-recovery: frequent poll of the durable Redis mail queue
15
+ * - avatar-cleanup: retry removal of detached files and abandoned uploads
14
16
  */
15
17
 
16
18
  import type { FastifyInstance } from 'fastify';
17
19
  import { startCleanupExpiredAuthJob } from './cleanup-expired-auth.job.js';
18
20
  import { startCleanupDeletedAccountsJob } from './cleanup-deleted-accounts.job.js';
19
21
  import { startRefreshCloudflareRangesJob } from './refresh-cloudflare-ranges.job.js';
22
+ import { startPasswordRecoveryJob } from '@modules/auth/recovery.queue.js';
23
+ import { startAvatarCleanupJob } from '@modules/users/avatar-cleanup.js';
20
24
 
21
25
  /**
22
26
  * Registers all background jobs
@@ -24,6 +28,8 @@ import { startRefreshCloudflareRangesJob } from './refresh-cloudflare-ranges.job
24
28
  * @param app - Fastify instance (used for onClose cleanup hooks)
25
29
  */
26
30
  export function registerJobs(app: FastifyInstance): void {
31
+ startPasswordRecoveryJob(app);
32
+ startAvatarCleanupJob(app);
27
33
  startCleanupExpiredAuthJob(app);
28
34
  startCleanupDeletedAccountsJob(app);
29
35
  startRefreshCloudflareRangesJob(app);
@@ -29,7 +29,7 @@ function makeRequest(tokenRole: 'USER' | 'ADMIN', sessionId: string | null = 'se
29
29
  return request as unknown as FastifyRequest;
30
30
  }
31
31
 
32
- const reply = {} as FastifyReply;
32
+ const reply = { header: vi.fn() } as unknown as FastifyReply;
33
33
 
34
34
  /** The live session found for the token, carrying its user's current state. */
35
35
  function mockDbUser(user: DbUser | null): void {
@@ -10,6 +10,7 @@ vi.mock('@config/env.js', () => ({
10
10
  env: {
11
11
  NODE_ENV: 'production',
12
12
  COOKIE_DOMAIN: '.example.test',
13
+ COOKIE_LEGACY_DOMAINS: ['previous.example.test', 'unrelated.test'],
13
14
  JWT_ACCESS_EXPIRY: '15m',
14
15
  JWT_REFRESH_EXPIRY: '7d',
15
16
  },
@@ -23,6 +24,8 @@ function fakeReply(): { reply: FastifyReply; set: Map<string, CookieOpts>; clear
23
24
  const set = new Map<string, CookieOpts>();
24
25
  const cleared: Array<[string, CookieOpts]> = [];
25
26
  const reply = {
27
+ header: vi.fn(),
28
+ request: { hostname: 'api.example.test' },
26
29
  setCookie: vi.fn((name: string, _value: string, opts: CookieOpts) => set.set(name, opts)),
27
30
  clearCookie: vi.fn((name: string, opts: CookieOpts) => cleared.push([name, opts])),
28
31
  } as unknown as FastifyReply;
@@ -76,6 +79,19 @@ describe('SameSite (never None, even with COOKIE_DOMAIN in production)', () => {
76
79
  });
77
80
 
78
81
  describe('clearAuthCookies', () => {
82
+ it('expires cookies at a previous domain only when the API host can clear it', () => {
83
+ const { reply, cleared } = fakeReply();
84
+ Object.assign(reply, { request: { hostname: 'api.previous.example.test' } });
85
+ clearAuthCookies(reply);
86
+ expect(cleared).toContainEqual(['refresh_token', expect.objectContaining({
87
+ domain: 'previous.example.test', path: '/api/v1/auth',
88
+ })]);
89
+ expect(cleared).toContainEqual(['auth_session', expect.objectContaining({
90
+ domain: 'previous.example.test', path: '/',
91
+ })]);
92
+ expect(cleared.some(([, options]) => options.domain === 'unrelated.test')).toBe(false);
93
+ });
94
+
79
95
  it('clears both the host-only tokens and any legacy domain-wide copies', () => {
80
96
  const { reply, cleared } = fakeReply();
81
97
  clearAuthCookies(reply);
@@ -40,6 +40,9 @@ beforeAll(async () => {
40
40
 
41
41
  typed.post('/schema', { schema: { body: signupSchema } }, async () => ({ ok: true }));
42
42
  typed.post('/wide', { schema: { body: wideSchema } }, async () => ({ ok: true }));
43
+ const strict = z.strictObject({ name: z.string() });
44
+ typed.post('/strict', { schema: { body: strict } }, async () => ({ ok: true }));
45
+ app.post('/strict-parse', async (request) => parseInput(strict, request.body));
43
46
  typed.get('/users/:id', { schema: { params: z.object({ id: z.uuid() }) } }, async () => ({ ok: true }));
44
47
  typed.get('/list', { schema: { querystring: z.object({ page: z.coerce.number().int().min(1) }) } }, async () => ({ ok: true }));
45
48
  app.post('/parse', async (request) => passwordSchema.parse(request.body));
@@ -48,7 +51,7 @@ beforeAll(async () => {
48
51
  throw new TooManyRequestsError('Too many requests. Try again in 1 minute.', 'RATE_LIMIT_EXCEEDED', 42);
49
52
  });
50
53
  app.get('/outbound', async () => {
51
- throw new OutboundHttpError('http', { status: 404, cause: new Error(`upstream said ${SECRET_VALUE}`) });
54
+ throw new OutboundHttpError('http', { status: 404 });
52
55
  });
53
56
  app.get('/boom', async () => {
54
57
  throw new Error(`internal detail ${SECRET_VALUE}`);
@@ -104,6 +107,13 @@ describe('global error handler', () => {
104
107
  expect(res.json().error.fields).toHaveLength(MAX_FIELD_ERRORS);
105
108
  });
106
109
 
110
+ it.each(['/strict', '/strict-parse'])('keeps submitted field names out of strict validation at %s', async (url) => {
111
+ const res = await app.inject({ method: 'POST', url, payload: { name: 'Fixture', [SECRET_VALUE]: true } });
112
+ expect(res.statusCode).toBe(422);
113
+ expectNoLeak(res.body);
114
+ expect(res.json().error.fields[0].message).toBe('Unexpected fields');
115
+ });
116
+
107
117
  it('schema.parse() inside a handler: same 422 shape', async () => {
108
118
  const res = await app.inject({ method: 'POST', url: '/parse', payload: { password: 'short' } });
109
119
  expect(res.statusCode).toBe(422);
@@ -134,6 +144,15 @@ describe('global error handler', () => {
134
144
  expectNoLeak(res.body);
135
145
  });
136
146
 
147
+ it('returns a fixed message when malformed JSON includes an unexpected value', async () => {
148
+ const res = await app.inject({
149
+ method: 'POST', url: '/schema', headers: { 'content-type': 'application/json' }, payload: SECRET_VALUE,
150
+ });
151
+ expect(res.statusCode).toBe(400);
152
+ expect(res.json().error).toEqual({ code: 'BAD_REQUEST', message: 'Bad request' });
153
+ expectNoLeak(res.body);
154
+ });
155
+
137
156
  it('AppError keeps its status, code and retryAfterSeconds, with no fields', async () => {
138
157
  const res = await app.inject({ method: 'GET', url: '/limited' });
139
158
  expect(res.statusCode).toBe(429);