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
@@ -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);
@@ -192,14 +192,14 @@ describe('httpClient', () => {
192
192
  expect((thrown as InternalError).code).toBe('INTERNAL_ERROR');
193
193
  });
194
194
 
195
- it('should log the error before throwing', () => {
195
+ it('logs a fixed message when setup fails', () => {
196
196
  const err = new Error('setup fail');
197
197
  try {
198
198
  captured.requestRejected!(err);
199
199
  } catch {
200
200
  // expected
201
201
  }
202
- expect(logger.error).toHaveBeenCalledWith({ err }, '[HTTP] Request setup failed');
202
+ expect(logger.error).toHaveBeenCalledWith('[HTTP] Request setup failed');
203
203
  });
204
204
 
205
205
  it('should not call logger.debug on the error path', () => {
@@ -298,7 +298,7 @@ describe('httpClient', () => {
298
298
  expect((thrown as InternalError).code).toBe('INTERNAL_ERROR');
299
299
  });
300
300
 
301
- it('should log method, url, status, and message', () => {
301
+ it('logs a method, sanitized URL, status and typed failure kind', () => {
302
302
  try {
303
303
  captured.responseRejected!(
304
304
  buildAxiosError({
@@ -311,7 +311,7 @@ describe('httpClient', () => {
311
311
  // expected
312
312
  }
313
313
  expect(logger.error).toHaveBeenCalledWith(
314
- { method: 'POST', url: '/upload', status: 413, message: 'Payload Too Large' },
314
+ { method: 'POST', url: '/upload', status: 413, kind: 'http' },
315
315
  '[HTTP] Outbound request failed',
316
316
  );
317
317
  });
@@ -334,7 +334,7 @@ describe('httpClient', () => {
334
334
  const minimalError = { isAxiosError: true, message: 'timeout' };
335
335
  expect(() => captured.responseRejected!(minimalError)).toThrow(InternalError);
336
336
  expect(logger.error).toHaveBeenCalledWith(
337
- { method: undefined, url: undefined, status: undefined, message: 'timeout' },
337
+ { method: undefined, url: undefined, status: undefined, kind: 'network' },
338
338
  '[HTTP] Outbound request failed',
339
339
  );
340
340
  });
@@ -367,14 +367,14 @@ describe('httpClient', () => {
367
367
  );
368
368
  });
369
369
 
370
- it('should log with the generic message and err field', () => {
370
+ it('logs a fixed message when an unexpected outbound error occurs', () => {
371
371
  const err = new Error('network failure');
372
372
  try {
373
373
  captured.responseRejected!(err);
374
374
  } catch {
375
375
  // expected
376
376
  }
377
- expect(logger.error).toHaveBeenCalledWith({ err }, '[HTTP] Unexpected outbound error');
377
+ expect(logger.error).toHaveBeenCalledWith('[HTTP] Unexpected outbound error');
378
378
  });
379
379
 
380
380
  it('should throw InternalError for thrown string', () => {
@@ -479,10 +479,10 @@ describe('httpClient — secrets never logged, failures typed', () => {
479
479
  expect(thrown).toMatchObject({ kind, status, statusCode: 500, code: 'INTERNAL_ERROR', message: 'Outbound HTTP request failed' });
480
480
  });
481
481
 
482
- it('keeps the original error as a non-enumerable cause (never serialized with the error)', () => {
482
+ it('keeps the HTTP status without retaining the upstream error', () => {
483
483
  const thrown = reject({ response: { status: 500 } });
484
- expect((thrown as { cause?: unknown }).cause).toBeDefined();
485
- expect(Object.keys(thrown)).not.toContain('cause');
484
+ expect(thrown.status).toBe(500);
485
+ expect(thrown).not.toHaveProperty('cause');
486
486
  });
487
487
 
488
488
  it("keeps a guard's OutboundHttpError when it passes through the request chain", () => {
@@ -1,7 +1,7 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
2
  import { getRedis } from '@libs/redis.js';
3
3
  import { prisma } from '@libs/prisma.js';
4
- import { blockIp, getIpBlock, pruneExpiredAutoBlocks, recordRateLimitViolation, unblockIp } from '../ip-block.js';
4
+ import { blockIp, getIpBlock, pruneExpiredAutoBlocks, recordRateLimitViolation, syncBlockedIpsToRedis, unblockIp } from '../ip-block.js';
5
5
 
6
6
  // Self-contained env so ip-block.ts can read its threshold constants at import
7
7
  // time without loading/validating the real environment.
@@ -31,15 +31,14 @@ vi.mock('@libs/logger.js', () => ({
31
31
  }));
32
32
 
33
33
  const redisMock = {
34
- del: vi.fn(),
34
+ get: vi.fn(),
35
+ eval: vi.fn(),
35
36
  zadd: vi.fn(),
36
37
  incr: vi.fn(),
37
38
  expire: vi.fn(),
38
39
  sismember: vi.fn(),
39
40
  zscore: vi.fn(),
40
41
  zrem: vi.fn(),
41
- sadd: vi.fn(),
42
- srem: vi.fn(),
43
42
  zremrangebyscore: vi.fn(),
44
43
  };
45
44
 
@@ -89,8 +88,17 @@ describe('getIpBlock — block state with the time left', () => {
89
88
 
90
89
  it('cleans up an expired automatic block and reports no block', async () => {
91
90
  redisMock.zscore.mockResolvedValue(String(Date.now() / 1000 - 5));
91
+ redisMock.eval.mockResolvedValueOnce(null);
92
92
  expect(await getIpBlock('93.184.216.34')).toEqual({ blocked: false });
93
- expect(redisMock.zrem).toHaveBeenCalledWith('auto_blocked_ips', '93.184.216.34');
93
+ expect(redisMock.zrem).not.toHaveBeenCalled();
94
+ });
95
+
96
+ it('keeps an automatic block that was renewed during expiry cleanup', async () => {
97
+ redisMock.zscore.mockResolvedValue(String(Date.now() / 1000 - 5));
98
+ redisMock.eval.mockResolvedValueOnce(String(Date.now() / 1000 + 59.5));
99
+ expect(await getIpBlock('93.184.216.34')).toEqual({
100
+ blocked: true, permanent: false, retryAfterSeconds: 60,
101
+ });
94
102
  });
95
103
 
96
104
  it('fails open when Redis is down', async () => {
@@ -107,16 +115,22 @@ describe('blockIp / unblockIp — one spelling, no self-lockout', () => {
107
115
  beforeEach(() => {
108
116
  vi.clearAllMocks();
109
117
  vi.mocked(getRedis).mockReturnValue(redisMock as never);
118
+ redisMock.get.mockResolvedValue(null);
119
+ redisMock.eval.mockResolvedValue(1);
110
120
  vi.mocked(prisma.blockedIp.findUnique).mockResolvedValue(null);
121
+ vi.mocked(prisma.blockedIp.findMany).mockResolvedValue([]);
111
122
  vi.mocked(prisma.blockedIp.create).mockImplementation((async ({ data }: { data: { ip: string } }) => ({
112
123
  id: 'b1', ip: data.ip, reason: null, blockedBy: 'admin-1', createdAt: new Date(),
113
124
  })) as never);
114
125
  });
115
126
 
116
127
  it('stores any spelling of an address in its canonical form, in the DB and in Redis', async () => {
128
+ vi.mocked(prisma.blockedIp.findMany).mockResolvedValueOnce([{ ip: '2001:db8::1' }] as never);
117
129
  const blocked = await blockIp('2001:0DB8:0000::0001', 'admin-1', undefined, ADMIN_IP);
118
130
  expect(blocked.ip).toBe('2001:db8::1');
119
- expect(redisMock.sadd).toHaveBeenCalledWith('blocked_ips', '2001:db8::1');
131
+ expect(redisMock.eval).toHaveBeenCalledWith(
132
+ expect.any(String), 2, 'blocked_ips', 'blocked_ips:revision', '', expect.any(String), '2001:db8::1',
133
+ );
120
134
 
121
135
  await blockIp('::ffff:203.0.113.7', 'admin-1', undefined, ADMIN_IP);
122
136
  expect(vi.mocked(prisma.blockedIp.create).mock.calls[1]?.[0]).toMatchObject({ data: { ip: '203.0.113.7' } });
@@ -154,11 +168,29 @@ describe('blockIp / unblockIp — one spelling, no self-lockout', () => {
154
168
  it('unblocks by the canonical form, in the DB and both Redis lists', async () => {
155
169
  await unblockIp('2001:DB8::1');
156
170
  expect(prisma.blockedIp.deleteMany).toHaveBeenCalledWith({ where: { ip: '2001:db8::1' } });
157
- expect(redisMock.srem).toHaveBeenCalledWith('blocked_ips', '2001:db8::1');
171
+ expect(redisMock.eval).toHaveBeenCalledWith(
172
+ expect.any(String), 2, 'blocked_ips', 'blocked_ips:revision', '', expect.any(String),
173
+ );
158
174
  expect(redisMock.zrem).toHaveBeenCalledWith('auto_blocked_ips', '2001:db8::1');
159
175
  });
160
176
  });
161
177
 
178
+ it('reads MySQL again when another replica wins the block publication', async () => {
179
+ vi.clearAllMocks();
180
+ vi.mocked(getRedis).mockReturnValue(redisMock as never);
181
+ redisMock.get.mockResolvedValueOnce('previous').mockResolvedValueOnce('current');
182
+ redisMock.eval.mockResolvedValueOnce(0).mockResolvedValueOnce(1);
183
+ vi.mocked(prisma.blockedIp.findMany)
184
+ .mockResolvedValueOnce([{ ip: '198.51.100.72' }] as never)
185
+ .mockResolvedValueOnce([{ ip: '198.51.100.73' }] as never);
186
+
187
+ await syncBlockedIpsToRedis();
188
+
189
+ expect(redisMock.eval).toHaveBeenNthCalledWith(
190
+ 2, expect.any(String), 2, 'blocked_ips', 'blocked_ips:revision', 'current', expect.any(String), '198.51.100.73',
191
+ );
192
+ });
193
+
162
194
  describe('pruneExpiredAutoBlocks', () => {
163
195
  beforeEach(() => {
164
196
  vi.clearAllMocks();
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import pino from 'pino';
7
7
  import { describe, expect, it } from 'vitest';
8
- import { REDACT_PATHS } from '@libs/logger.js';
8
+ import { logger, REDACT_PATHS } from '@libs/logger.js';
9
9
 
10
10
  function logged(obj: Record<string, unknown>): string {
11
11
  const lines: string[] = [];
@@ -17,6 +17,15 @@ function logged(obj: Record<string, unknown>): string {
17
17
  const SECRET = 'leak-canary-9W4K';
18
18
 
19
19
  describe('log redaction', () => {
20
+ it('serializes an error without its message, nested cause or request data', () => {
21
+ const error = Object.assign(new TypeError(`fixture error ${SECRET}`, { cause: new Error(SECRET) }), {
22
+ code: 'P2025', config: { headers: { authorization: SECRET } },
23
+ });
24
+ const { err } = (logger as unknown as { [pino.symbols.serializersSym]: { err: (value: unknown) => unknown } })[pino.symbols.serializersSym];
25
+ const serialized = err(error);
26
+ expect(serialized).toMatchObject({ type: 'TypeError', code: 'P2025' });
27
+ expect(JSON.stringify(serialized)).not.toContain(SECRET);
28
+ });
20
29
  it('removes secrets at the top level and one, two and three levels deep', () => {
21
30
  for (const obj of [
22
31
  { password: SECRET },