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,159 @@
1
+ import { beforeEach, expect, it, vi } from 'vitest';
2
+ import type { FastifyInstance } from 'fastify';
3
+ import { env } from '@config/env.js';
4
+ import { enqueueRecovery, startPasswordRecoveryJob } from '../recovery.queue.js';
5
+ import { findUserByEmail } from '../auth.repo.js';
6
+ import { issueRecoveryToken } from '../recovery.store.js';
7
+ import { sendEmail } from '@libs/email.js';
8
+ import { startRecurringJob } from '@/jobs/schedule.js';
9
+ import { testUsers } from '@/test/setup.js';
10
+
11
+ const redis = vi.hoisted(() => ({
12
+ status: 'ready',
13
+ eval: vi.fn(),
14
+ xgroup: vi.fn(),
15
+ xautoclaim: vi.fn(),
16
+ xreadgroup: vi.fn(),
17
+ xpending: vi.fn(),
18
+ }));
19
+ vi.mock('@libs/redis.js', () => ({ getRedis: (): typeof redis => redis }));
20
+ vi.mock('../auth.repo.js');
21
+ vi.mock('../recovery.store.js');
22
+ vi.mock('@libs/email.js');
23
+ vi.mock('@/jobs/schedule.js');
24
+
25
+ const address = 'test@example.com';
26
+ const user = testUsers.validUser;
27
+ let id: string;
28
+
29
+ beforeEach(() => {
30
+ vi.resetAllMocks();
31
+ redis.status = 'ready';
32
+ id = `${Date.now()}-0`;
33
+ redis.eval.mockResolvedValue(0);
34
+ redis.xgroup.mockResolvedValue('OK');
35
+ redis.xautoclaim.mockResolvedValue(['0-0', [], []]);
36
+ redis.xreadgroup.mockResolvedValue(null);
37
+ vi.mocked(findUserByEmail).mockResolvedValue(user);
38
+ vi.mocked(issueRecoveryToken).mockResolvedValue(true);
39
+ });
40
+
41
+ function worker(): { run: () => Promise<unknown>; close: () => Promise<void>; consumer: () => string } {
42
+ const addHook = vi.fn();
43
+ startPasswordRecoveryJob({ addHook } as unknown as FastifyInstance);
44
+ const run = vi.mocked(startRecurringJob).mock.lastCall![1].run;
45
+ return {
46
+ run,
47
+ close: addHook.mock.lastCall![1] as () => Promise<void>,
48
+ consumer: () => redis.xautoclaim.mock.lastCall?.[2] as string,
49
+ };
50
+ }
51
+
52
+ function claim(attempt: number, entry = id): void {
53
+ redis.xpending.mockImplementation(async () => [[entry, redis.xautoclaim.mock.lastCall![2], 0, attempt]]);
54
+ }
55
+
56
+ function newJob(entry = id, fields = ['email', address]): void {
57
+ redis.xreadgroup.mockResolvedValueOnce([['pw-recovery:jobs', [[entry, fields]]]]);
58
+ }
59
+
60
+ it('admits requests independently of account lookup', async () => {
61
+ await expect(enqueueRecovery(address)).resolves.toBeUndefined();
62
+ expect(findUserByEmail).not.toHaveBeenCalled();
63
+ });
64
+
65
+ it('maps quota and admission failure to their public errors', async () => {
66
+ redis.eval.mockResolvedValueOnce(20_000).mockResolvedValueOnce(-1).mockRejectedValueOnce(new Error('private'));
67
+ await expect(enqueueRecovery(address)).rejects.toMatchObject({ code: 'EMAIL_RATE_LIMITED', retryAfterSeconds: 20 });
68
+ await expect(enqueueRecovery(address)).rejects.toMatchObject({ statusCode: 503 });
69
+ await expect(enqueueRecovery(address)).rejects.toMatchObject({ statusCode: 503 });
70
+ });
71
+
72
+ it('sends only to the stored account address and finishes delivery', async () => {
73
+ const job = worker();
74
+ newJob();
75
+ claim(1);
76
+ await job.run();
77
+ expect(sendEmail).toHaveBeenCalledWith(expect.objectContaining({
78
+ to: user.email, idempotencyKey: expect.stringMatching(/^password-recovery\/[0-9a-f]{64}$/),
79
+ }));
80
+ expect(redis.eval).toHaveBeenCalledWith(expect.any(String), 1, 'pw-recovery:jobs', 'password-recovery', id, job.consumer());
81
+ });
82
+
83
+ it('keeps delivery keys distinct when deployments share a mail provider', async () => {
84
+ const job = worker();
85
+ newJob();
86
+ claim(1);
87
+ await job.run();
88
+
89
+ const originalUrl = env.CLIENT_URL;
90
+ try {
91
+ env.CLIENT_URL = 'https://other-deployment.example.test';
92
+ newJob(); // Independent Redis streams can assign the same ID.
93
+ await job.run();
94
+ } finally {
95
+ env.CLIENT_URL = originalUrl;
96
+ }
97
+ const keys = vi.mocked(sendEmail).mock.calls.map(([message]) => message.idempotencyKey);
98
+ expect(new Set(keys).size).toBe(2);
99
+ });
100
+
101
+ it('handles unknown accounts and obsolete generations without sending email', async () => {
102
+ const job = worker();
103
+ newJob();
104
+ claim(1);
105
+ vi.mocked(findUserByEmail).mockResolvedValueOnce(null);
106
+ await job.run();
107
+ newJob();
108
+ vi.mocked(issueRecoveryToken).mockResolvedValueOnce(false);
109
+ await job.run();
110
+ expect(sendEmail).not.toHaveBeenCalled();
111
+ expect(redis.eval).toHaveBeenCalledTimes(2);
112
+ });
113
+
114
+ it('preserves a failed delivery for a single retry with the same link and key', async () => {
115
+ const job = worker();
116
+ newJob();
117
+ claim(1);
118
+ vi.mocked(sendEmail).mockRejectedValueOnce(new Error('fixture failure'));
119
+ await job.run();
120
+ expect(redis.eval).not.toHaveBeenCalled();
121
+
122
+ redis.xautoclaim.mockResolvedValueOnce(['0-0', [[id, ['email', address]]], []]);
123
+ claim(2);
124
+ await job.run();
125
+ expect(vi.mocked(sendEmail).mock.calls[1]?.[0]).toEqual(vi.mocked(sendEmail).mock.calls[0]?.[0]);
126
+ expect(redis.eval).toHaveBeenCalledTimes(1);
127
+ });
128
+
129
+ it('discards expired and exhausted jobs without looking up any account', async () => {
130
+ const job = worker();
131
+ const expired = `${Date.now() - 301_000}-0`;
132
+ newJob(expired);
133
+ claim(1, expired);
134
+ await job.run();
135
+ newJob();
136
+ claim(3);
137
+ await job.run();
138
+ expect(findUserByEmail).not.toHaveBeenCalled();
139
+ expect(redis.eval).toHaveBeenCalledTimes(2);
140
+ });
141
+
142
+ it('joins an existing group and stops picking up work when closing', async () => {
143
+ const job = worker();
144
+ redis.xgroup.mockRejectedValueOnce(new Error('BUSYGROUP consumer already exists'));
145
+ await job.run();
146
+ expect(redis.xautoclaim).toHaveBeenCalledTimes(1);
147
+ await job.close();
148
+ await job.run();
149
+ expect(redis.xautoclaim).toHaveBeenCalledTimes(1);
150
+ });
151
+
152
+ it('does not send a job whose lease already belongs to another worker', async () => {
153
+ const job = worker();
154
+ newJob();
155
+ redis.xpending.mockResolvedValue([[id, 'other-worker', 0, 2]]);
156
+ await job.run();
157
+ expect(sendEmail).not.toHaveBeenCalled();
158
+ expect(redis.eval).not.toHaveBeenCalled();
159
+ });
@@ -5,8 +5,7 @@
5
5
  */
6
6
  import { beforeEach, describe, expect, it, vi } from 'vitest';
7
7
  import { prisma } from '@libs/prisma.js';
8
- import { sessionRepository } from '../session.repo.js';
9
- import { deleteRefreshTokensByUserId } from '../auth.repo.js';
8
+ import { revokeAccountCredentials } from '@libs/account-mutation.js';
10
9
 
11
10
  vi.mock('@libs/prisma.js', () => ({
12
11
  prisma: { session: { deleteMany: vi.fn() }, refreshToken: { deleteMany: vi.fn() } },
@@ -20,20 +19,16 @@ beforeEach(() => {
20
19
  });
21
20
 
22
21
  describe('keeping one session', () => {
23
- it('deleteOtherUserSessions deletes every session of the user but the kept one', async () => {
24
- await expect(sessionRepository.deleteOtherUserSessions('u1', 's-keep')).resolves.toBe(2);
22
+ it('deletes the other sessions and also revokes legacy refresh records', async () => {
23
+ await expect(revokeAccountCredentials(prisma, 'u1', 's-keep')).resolves.toBe(2);
25
24
  expect(prisma.session.deleteMany).toHaveBeenCalledWith({ where: { userId: 'u1', id: { not: 's-keep' } } });
26
- });
27
-
28
- it("deleteRefreshTokensByUserId with exceptSessionId keeps that session's tokens and deletes session-less ones", async () => {
29
- await deleteRefreshTokensByUserId('u1', { exceptSessionId: 's-keep' });
30
25
  expect(prisma.refreshToken.deleteMany).toHaveBeenCalledWith({
31
26
  where: { userId: 'u1', OR: [{ sessionId: null }, { sessionId: { not: 's-keep' } }] },
32
27
  });
33
28
  });
34
29
 
35
- it('deleteRefreshTokensByUserId without options still deletes all of them', async () => {
36
- await deleteRefreshTokensByUserId('u1');
30
+ it('revokes all sessions and refresh credentials when no session is retained', async () => {
31
+ await revokeAccountCredentials(prisma, 'u1');
37
32
  expect(prisma.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { userId: 'u1' } });
38
33
  });
39
34
  });
@@ -51,7 +51,7 @@ const accessOnly = (jar: CookieJar): string => `access_token=${jar.get('access_t
51
51
  async function resetTokenFor(email: string): Promise<string> {
52
52
  const r = await call(app, 'POST', '/auth/forgot-password', { payload: { email } });
53
53
  expect(r.status).toBe(200);
54
- return tokenOf(mail.to(email).filter((e) => /reset-password/.test(e.link ?? '')).at(-1)?.link ?? null);
54
+ return tokenOf((await mail.waitFor(email, (e) => /reset-password/.test(e.link ?? ''))).at(-1)?.link ?? null);
55
55
  }
56
56
 
57
57
  describe('tokens are stored as fingerprints', () => {
@@ -7,14 +7,17 @@
7
7
  import { createHash } from 'node:crypto';
8
8
  import { describe, expect, it, vi, beforeEach } from 'vitest';
9
9
  import { hashToken } from '@libs/token-hash.js';
10
- import { testUsers } from '@/test/setup.js';
10
+ import { issueRecoveryToken, findRecoveryOwner } from '../recovery.store.js';
11
11
 
12
12
  const sha256 = (raw: string): string => createHash('sha256').update(raw).digest('hex');
13
13
 
14
14
  const prismaMock = vi.hoisted(() => ({
15
15
  refreshToken: { create: vi.fn(), findUnique: vi.fn(), delete: vi.fn(), deleteMany: vi.fn() },
16
- session: { update: vi.fn() },
17
- $transaction: vi.fn(),
16
+ retiredRefreshToken: { create: vi.fn(), findFirst: vi.fn() },
17
+ session: { create: vi.fn(), findFirst: vi.fn(), update: vi.fn(), deleteMany: vi.fn() },
18
+ user: { update: vi.fn() },
19
+ $transaction: vi.fn(),
20
+ $queryRaw: vi.fn().mockResolvedValue([{}]),
18
21
  }));
19
22
  // rotateRefreshToken runs an interactive transaction: hand it the same mock as `tx`.
20
23
  vi.mock('@libs/prisma.js', () => ({
@@ -23,24 +26,15 @@ vi.mock('@libs/prisma.js', () => ({
23
26
  isPrismaWriteConflict: (e: unknown): boolean => (e as { code?: string })?.code === 'P2034',
24
27
  }));
25
28
 
26
- const redisMock = vi.hoisted(() => ({ status: 'ready', get: vi.fn(), set: vi.fn(), del: vi.fn(), getdel: vi.fn() }));
29
+ const redisMock = vi.hoisted(() => ({ get: vi.fn(), eval: vi.fn() }));
27
30
  vi.mock('@libs/redis.js', () => ({ getRedis: (): typeof redisMock => redisMock }));
28
31
 
29
- const sentEmails = vi.hoisted(() => [] as Array<{ html: string }>);
30
- vi.mock('@libs/email.js', () => ({ sendEmail: vi.fn(async (msg: { html: string }) => void sentEmails.push(msg)) }));
31
- vi.mock('@libs/email-quota.js', () => ({ consumeEmailQuota: vi.fn() }));
32
- vi.mock('@libs/password.js', () => ({ hashPassword: vi.fn(async () => 'new-hash'), verifyPassword: vi.fn() }));
33
- vi.mock('../session.repo.js', () => ({ sessionRepository: { deleteAllUserSessions: vi.fn() } }));
34
-
35
- // Imported after the mocks.
36
32
  const authRepo = await import('../auth.repo.js');
37
- const authService = await import('../auth.service.js');
38
33
 
39
34
  beforeEach(() => {
40
- vi.clearAllMocks();
41
- sentEmails.length = 0;
35
+ vi.resetAllMocks();
42
36
  });
43
-
37
+
44
38
  describe('hashToken', () => {
45
39
  it('is the SHA-256 hex of the token: 64 characters, deterministic, never the input', () => {
46
40
  expect(hashToken('abc')).toBe(sha256('abc'));
@@ -63,57 +57,134 @@ describe('refresh tokens in MySQL', () => {
63
57
  expect(prismaMock.refreshToken.delete).toHaveBeenCalledWith({ where: { token: sha256(raw) } });
64
58
  });
65
59
 
66
- const newData = { token: 'new-raw', userId: 'u1', sessionId: 's1', expiresAt: new Date() };
60
+ const inFuture = new Date('2099-01-01');
61
+ const getExpiry = (): Date => inFuture;
62
+ const active = { id: 'r1', userId: 'u1', sessionId: 's1', expiresAt: inFuture };
67
63
  const runTx = (): void => {
68
64
  prismaMock.$transaction.mockImplementation(async (fn: (tx: typeof prismaMock) => unknown) => fn(prismaMock));
65
+ prismaMock.$queryRaw.mockResolvedValue([{ role: 'USER', isActive: true, deletedAt: null, emailVerifiedAt: new Date() }]);
66
+ prismaMock.refreshToken.findUnique.mockResolvedValue(active);
67
+ prismaMock.session.findFirst.mockResolvedValue({ id: 's1', expiresAt: inFuture });
69
68
  };
70
69
 
71
- it('rotation removes the old fingerprint with a counted delete and stores the new one', async () => {
70
+ it('rotation stores the new refresh and the committed old fingerprint in the same transaction', async () => {
72
71
  runTx();
73
- prismaMock.refreshToken.deleteMany.mockResolvedValue({ count: 1 });
74
- await expect(authRepo.rotateRefreshToken(raw, newData)).resolves.toBe(true);
75
- expect(prismaMock.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { token: sha256(raw) } });
72
+ await expect(authRepo.rotateRefreshToken(raw, 'new-raw', getExpiry)).resolves.toEqual({
73
+ kind: 'issued', claims: { userId: 'u1', sessionId: 's1', role: 'USER' },
74
+ });
75
+ expect(prismaMock.refreshToken.delete).toHaveBeenCalledWith({ where: { id: 'r1' } });
76
76
  expect(prismaMock.refreshToken.create).toHaveBeenCalledWith({
77
77
  data: expect.objectContaining({ token: sha256('new-raw') }),
78
78
  });
79
+ expect(prismaMock.retiredRefreshToken.create).toHaveBeenCalledWith({
80
+ data: { fingerprint: sha256(raw), sessionId: 's1', expiresAt: expect.any(Date) },
81
+ });
79
82
  });
80
83
 
81
- it('exactly one parallel rotation wins: the one that removed nothing creates nothing', async () => {
84
+ it('a losing rotation has no write and sees only a committed retirement', async () => {
82
85
  runTx();
83
- prismaMock.refreshToken.deleteMany.mockResolvedValue({ count: 0 }); // a parallel refresh removed it
84
- await expect(authRepo.rotateRefreshToken(raw, newData)).resolves.toBe(false);
86
+ prismaMock.refreshToken.findUnique.mockResolvedValueOnce(active).mockResolvedValueOnce(null);
87
+ prismaMock.retiredRefreshToken.findFirst.mockResolvedValue({ sessionId: 's1', session: { userId: 'u1' } });
88
+ await expect(authRepo.rotateRefreshToken(raw, 'new-raw', getExpiry)).resolves.toEqual({ kind: 'rotated' });
85
89
  expect(prismaMock.refreshToken.create).not.toHaveBeenCalled();
86
90
  expect(prismaMock.session.update).not.toHaveBeenCalled();
87
91
  });
88
92
 
89
- it('a write conflict with the parallel transaction counts as a lost race, not a 500', async () => {
93
+ it('checks expiry after the locks instead of relying on the initial token lookup', async () => {
94
+ runTx();
95
+ prismaMock.refreshToken.findUnique.mockResolvedValueOnce(active)
96
+ .mockResolvedValueOnce({ ...active, expiresAt: new Date(0) });
97
+ await expect(authRepo.rotateRefreshToken(raw, 'new-raw', getExpiry)).resolves.toEqual({ kind: 'expired-token' });
98
+ expect(prismaMock.refreshToken.create).not.toHaveBeenCalled();
99
+ });
100
+
101
+ it('refuses a session that expired while the transaction waited', async () => {
102
+ runTx();
103
+ prismaMock.session.findFirst.mockResolvedValue({ id: 's1', expiresAt: new Date(0) });
104
+ await expect(authRepo.rotateRefreshToken(raw, 'new-raw', getExpiry)).resolves.toEqual({ kind: 'expired-session' });
105
+ expect(prismaMock.session.update).not.toHaveBeenCalled();
106
+ });
107
+
108
+ it('returns 503 after three write conflicts without labelling them as rotations', async () => {
109
+ prismaMock.refreshToken.findUnique.mockResolvedValue(active);
90
110
  prismaMock.$transaction.mockRejectedValue(Object.assign(new Error('write conflict'), { code: 'P2034' }));
91
- await expect(authRepo.rotateRefreshToken(raw, newData)).resolves.toBe(false);
111
+ await expect(authRepo.rotateRefreshToken(raw, 'new-raw', getExpiry)).rejects.toMatchObject({ statusCode: 503 });
112
+ expect(prismaMock.$transaction).toHaveBeenCalledTimes(3);
113
+ });
114
+
115
+ it('logs out the same session when its refresh token rotated during the request', async () => {
116
+ runTx();
117
+ prismaMock.refreshToken.findUnique.mockResolvedValueOnce(active).mockResolvedValueOnce(null);
118
+ prismaMock.retiredRefreshToken.findFirst.mockResolvedValue({ sessionId: 's1', session: { userId: 'u1' } });
119
+ await authRepo.revokeSession(raw);
120
+ expect(prismaMock.session.deleteMany).toHaveBeenCalledWith({ where: { id: 's1', userId: 'u1' } });
121
+ expect(prismaMock.refreshToken.deleteMany).not.toHaveBeenCalled();
122
+ });
123
+
124
+ it('uses the session and user from verified access claims for access-only logout', async () => {
125
+ runTx();
126
+ await authRepo.revokeSession(undefined, { userId: 'u1', sessionId: 's1' });
127
+ expect(prismaMock.refreshToken.findUnique).not.toHaveBeenCalled();
128
+ expect(prismaMock.session.deleteMany).toHaveBeenCalledWith({ where: { id: 's1', userId: 'u1' } });
92
129
  });
93
130
  });
94
131
 
95
132
  describe('password-reset tokens in Redis', () => {
96
- it('forgotPassword stores only the fingerprint; the raw token exists only in the email', async () => {
97
- vi.spyOn(authRepo, 'findUserByEmail').mockResolvedValue(testUsers.validUser);
98
- redisMock.get.mockResolvedValue(null);
99
-
100
- await authService.forgotPassword(testUsers.validUser.email);
101
-
102
- const raw = /token=([0-9a-f]{64})/.exec(sentEmails[0]?.html ?? '')?.[1];
103
- expect(raw).toBeDefined();
104
- const stored = JSON.stringify(redisMock.set.mock.calls);
105
- expect(stored).not.toContain(raw as string);
106
- expect(redisMock.set).toHaveBeenCalledWith(`pw-reset:${sha256(raw as string)}`, testUsers.validUser.id, 'EX', 3600);
107
- expect(redisMock.set).toHaveBeenCalledWith(`pw-reset-user:${testUsers.validUser.id}`, sha256(raw as string), 'EX', 3600);
133
+ const raw = 'private-fixture-token';
134
+ const fingerprint = sha256(raw);
135
+
136
+ it('issues a reset record and pointer without passing the raw token to Redis', async () => {
137
+ redisMock.eval.mockResolvedValue(1);
138
+ await expect(issueRecoveryToken('u1', raw, '100-0')).resolves.toBe(true);
139
+ expect(JSON.stringify(redisMock.eval.mock.calls)).not.toContain(raw);
140
+ expect(redisMock.eval).toHaveBeenCalledWith(
141
+ expect.any(String), 3, `pw-reset:${fingerprint}`, 'pw-reset-user:u1', 'pw-reset-order:u1',
142
+ 'u1', fingerprint, '100-0', 3600, 'pw-reset:',
143
+ );
144
+ });
145
+
146
+ it('looks up the account by the emailed token fingerprint', async () => {
147
+ redisMock.get.mockResolvedValue('u1');
148
+ await expect(findRecoveryOwner(raw)).resolves.toBe('u1');
149
+ expect(redisMock.get).toHaveBeenCalledWith(`pw-reset:${fingerprint}`);
150
+ });
151
+ });
152
+
153
+ describe('the password recovery transaction', () => {
154
+ const userId = 'u1';
155
+ const currentHash = 'current-hash';
156
+ const nextHash = 'next-hash';
157
+
158
+ function useTransaction(): void {
159
+ prismaMock.$transaction.mockImplementation(async (run: (tx: typeof prismaMock) => unknown) => run(prismaMock));
160
+ prismaMock.$queryRaw.mockResolvedValueOnce([{ password: currentHash, deletedAt: null }]);
161
+ }
162
+
163
+ it('uses the same transaction for the password and every session or refresh credential', async () => {
164
+ useTransaction();
165
+ await expect(authRepo.commitPasswordRecovery(userId, currentHash, nextHash)).resolves.toBe(true);
166
+ expect(prismaMock.user.update).toHaveBeenCalledWith({ where: { id: userId }, data: { password: nextHash } });
167
+ expect(prismaMock.session.deleteMany).toHaveBeenCalledWith({ where: { userId } });
168
+ expect(prismaMock.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { userId } });
169
+ });
170
+
171
+ it('preserves a password that changed before the lock was obtained', async () => {
172
+ useTransaction();
173
+ await expect(authRepo.commitPasswordRecovery(userId, 'outdated-hash', nextHash)).resolves.toBe(false);
174
+ expect(prismaMock.user.update).not.toHaveBeenCalled();
108
175
  });
109
176
 
110
- it('resetPassword looks the emailed (raw) token up by its fingerprint', async () => {
111
- redisMock.getdel.mockResolvedValue(testUsers.validUser.id);
112
- vi.spyOn(authRepo, 'findUserById').mockResolvedValue(testUsers.validUser);
113
- vi.spyOn(authRepo, 'updateUserPassword').mockResolvedValue(undefined);
114
- vi.spyOn(authRepo, 'deleteRefreshTokensByUserId').mockResolvedValue(undefined);
177
+ it('stops after three transient transaction conflicts', async () => {
178
+ prismaMock.$transaction.mockRejectedValue(Object.assign(new Error('write conflict'), { code: 'P2034' }));
179
+ await expect(authRepo.commitPasswordRecovery(userId, currentHash, nextHash)).rejects.toThrow('write conflict');
180
+ expect(prismaMock.$transaction).toHaveBeenCalledTimes(3);
181
+ });
115
182
 
116
- await authService.resetPassword('raw-reset-token', 'New-Passw0rd-123!');
117
- expect(redisMock.getdel).toHaveBeenCalledWith(`pw-reset:${sha256('raw-reset-token')}`);
183
+ it('refuses a sign-in verified before the recovered password was committed', async () => {
184
+ useTransaction();
185
+ await expect(authRepo.createLoginSession({
186
+ userId, verifiedPasswordHash: 'outdated-hash', refreshToken: 'fixture', expiresAt: new Date(),
187
+ })).resolves.toBeNull();
188
+ expect(prismaMock.session.create).not.toHaveBeenCalled();
118
189
  });
119
190
  });
@@ -0,0 +1,64 @@
1
+ import { getRedis } from '@libs/redis.js';
2
+ import { hashToken } from '@libs/token-hash.js';
3
+
4
+ const ttlSeconds = 3_600;
5
+
6
+ // Keep the existing token and pointer formats for coordinated upgrades. The
7
+ // order key outlives consumption so a retry cannot resurrect a redeemed link.
8
+ const issueCurrent = `
9
+ local previous = redis.call('GET', KEYS[3])
10
+ if previous then
11
+ local oldMs, oldSeq = string.match(previous, '^(%d+)-(%d+)$')
12
+ local newMs, newSeq = string.match(ARGV[3], '^(%d+)-(%d+)$')
13
+ oldMs, oldSeq, newMs, newSeq = tonumber(oldMs), tonumber(oldSeq), tonumber(newMs), tonumber(newSeq)
14
+ if oldMs > newMs or (oldMs == newMs and oldSeq > newSeq) then return 0 end
15
+ if previous == ARGV[3] then
16
+ if redis.call('GET', KEYS[2]) == ARGV[2] and redis.call('GET', KEYS[1]) == ARGV[1] then return 1 end
17
+ return 0
18
+ end
19
+ end
20
+ local current = redis.call('GET', KEYS[2])
21
+ if current then redis.call('DEL', ARGV[5] .. current) end
22
+ redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[4])
23
+ redis.call('SET', KEYS[2], ARGV[2], 'EX', ARGV[4])
24
+ redis.call('SET', KEYS[3], ARGV[3], 'EX', ARGV[4])
25
+ return 1
26
+ `;
27
+
28
+ const consumeCurrent = `
29
+ if redis.call('GET', KEYS[1]) ~= ARGV[1] or redis.call('GET', KEYS[2]) ~= ARGV[2] then return 0 end
30
+ redis.call('DEL', KEYS[1], KEYS[2])
31
+ return 1
32
+ `;
33
+
34
+ interface AuthLinkStore {
35
+ issue(userId: string, token: string, deliveryId: string): Promise<boolean>;
36
+ findOwner(token: string): Promise<string | null>;
37
+ consume(userId: string, token: string): Promise<boolean>;
38
+ }
39
+
40
+ /** Each feature keeps its existing fingerprint and per-account pointer namespace. */
41
+ export function authLinkStore(tokenPrefix: string, currentPrefix: string, orderPrefix: string): AuthLinkStore {
42
+ return {
43
+ async issue(userId: string, token: string, deliveryId: string): Promise<boolean> {
44
+ const fingerprint = hashToken(token);
45
+ return await getRedis().eval(
46
+ issueCurrent, 3, tokenPrefix + fingerprint, currentPrefix + userId, orderPrefix + userId,
47
+ userId, fingerprint, deliveryId, ttlSeconds, tokenPrefix,
48
+ ) === 1;
49
+ },
50
+
51
+ // This lookup grants no authority. Consumption rechecks the live pointer.
52
+ findOwner(token: string): Promise<string | null> {
53
+ return getRedis().get(tokenPrefix + hashToken(token));
54
+ },
55
+
56
+ async consume(userId: string, token: string): Promise<boolean> {
57
+ const fingerprint = hashToken(token);
58
+ return await getRedis().eval(
59
+ consumeCurrent, 2, tokenPrefix + fingerprint, currentPrefix + userId,
60
+ userId, fingerprint,
61
+ ) === 1;
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,124 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { FastifyInstance } from 'fastify';
3
+ import { EMAIL_PER_ADDRESS } from '@config/rate-limit.config.js';
4
+ import { emailQuotaExceeded, emailQuotaKey, type EmailQuotaBucket } from '@libs/email-quota.js';
5
+ import { logger } from '@libs/logger.js';
6
+ import { getRedis } from '@libs/redis.js';
7
+ import { startRecurringJob } from '@/jobs/schedule.js';
8
+ import { ServiceUnavailableError } from '@shared/errors/errors.js';
9
+
10
+ const maxAgeMs = 5 * 60_000;
11
+ // A healthy delivery finishes before another replica can claim its entry.
12
+ const retryAfterMs = 30_000;
13
+
14
+ // Capacity, normalized address quota and enqueue are one decision. A job can
15
+ // be accepted without a lookup, and failed admission never charges the quota.
16
+ const enqueue = `
17
+ if redis.call('XLEN', KEYS[1]) >= tonumber(ARGV[1]) then return -1 end
18
+ if #KEYS == 2 then
19
+ local used = tonumber(redis.call('GET', KEYS[2]) or '0')
20
+ if used >= tonumber(ARGV[2]) then
21
+ local ttl = redis.call('PTTL', KEYS[2])
22
+ if ttl < 0 then
23
+ redis.call('PEXPIRE', KEYS[2], ARGV[3])
24
+ ttl = tonumber(ARGV[3])
25
+ end
26
+ return math.max(1, ttl)
27
+ end
28
+ end
29
+ redis.call('XADD', KEYS[1], '*', 'email', ARGV[4])
30
+ if #KEYS == 2 then
31
+ redis.call('INCR', KEYS[2])
32
+ if redis.call('PTTL', KEYS[2]) < 0 then redis.call('PEXPIRE', KEYS[2], ARGV[3]) end
33
+ end
34
+ return 0
35
+ `;
36
+
37
+ export async function enqueueAuthMail(
38
+ stream: string, email: string, quota: EmailQuotaBucket | 'none', capacity: number, feature: string,
39
+ ): Promise<void> {
40
+ const keys = quota === 'none' ? [stream] : [stream, emailQuotaKey(email, quota)];
41
+ const unavailable = (): ServiceUnavailableError =>
42
+ new ServiceUnavailableError(feature + ' is temporarily unavailable. Please try again in a few minutes.');
43
+ let status: number;
44
+ try {
45
+ status = Number(await getRedis().eval(
46
+ enqueue, keys.length, ...keys, capacity, EMAIL_PER_ADDRESS.max, EMAIL_PER_ADDRESS.timeWindow, email,
47
+ ));
48
+ } catch {
49
+ // Redis failures can echo command arguments including the address.
50
+ throw unavailable();
51
+ }
52
+ if (status > 0) throw emailQuotaExceeded(status);
53
+ if (status !== 0) throw unavailable();
54
+ }
55
+
56
+ type MailDelivery = (id: string, email: string) => Promise<void>;
57
+
58
+ type StreamEntry = [id: string, fields: string[]];
59
+ type PendingEntry = [id: string, consumer: string, idleMs: number, deliveries: number];
60
+
61
+ const finish = `
62
+ local mine = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
63
+ if not mine[1] or mine[1][2] ~= ARGV[3] then return 0 end
64
+ redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
65
+ return redis.call('XDEL', KEYS[1], ARGV[2])
66
+ `;
67
+
68
+ export function startAuthMailWorker(app: FastifyInstance, stream: string, group: string, deliver: MailDelivery): void {
69
+ const consumer = randomUUID();
70
+ let initialized = false;
71
+ let closing = false;
72
+ let cursor = '0-0';
73
+ app.addHook('preClose', async () => { closing = true; });
74
+
75
+ startRecurringJob(app, {
76
+ name: group,
77
+ firstRunDelayMs: 250,
78
+ intervalMs: 250,
79
+ async run() {
80
+ if (closing) return;
81
+ try {
82
+ const redis = getRedis();
83
+ if (redis.status !== 'ready') return;
84
+ if (!initialized) {
85
+ try {
86
+ await redis.xgroup('CREATE', stream, group, '0', 'MKSTREAM');
87
+ } catch (error) {
88
+ if (!(error instanceof Error) || !error.message.startsWith('BUSYGROUP')) throw error;
89
+ }
90
+ initialized = true;
91
+ }
92
+ const [nextCursor, pending] = await redis.xautoclaim(
93
+ stream, group, consumer, retryAfterMs, cursor, 'COUNT', 1,
94
+ ) as [string, StreamEntry[], string[]];
95
+ cursor = nextCursor;
96
+ const fresh = pending.length || closing ? null : await redis.xreadgroup(
97
+ 'GROUP', group, consumer, 'COUNT', 1, 'STREAMS', stream, '>',
98
+ ) as [string, StreamEntry[]][] | null;
99
+ const entry = pending[0] ?? fresh?.[0]?.[1][0];
100
+ if (!entry || closing) return;
101
+ const [id, fields] = entry;
102
+ const claims = await redis.xpending(stream, group, id, id, 1) as PendingEntry[];
103
+ const claim = claims[0];
104
+ if (!claim || claim[1] !== consumer || closing) return;
105
+ const deliveries = claim[3];
106
+ if (deliveries <= 2 && Date.now() - Number(id.split('-')[0]) <= maxAgeMs) {
107
+ try {
108
+ if (fields.length === 2 && fields[0] === 'email' && fields[1]) await deliver(id, fields[1]);
109
+ } catch {
110
+ logger.warn({ job: group, attempt: deliveries }, '[AUTH] Mail delivery failed');
111
+ if (deliveries < 2) return; // Leave pending for a later claim.
112
+ }
113
+ }
114
+ await redis.eval(finish, 1, stream, group, id, consumer);
115
+ } catch {
116
+ // A Redis restart may remove the group. Recreate it on the next tick.
117
+ if (initialized) {
118
+ logger.warn({ job: group }, '[AUTH] Mail queue became unavailable');
119
+ initialized = false;
120
+ }
121
+ }
122
+ },
123
+ });
124
+ }
@@ -4,6 +4,7 @@ import { UnauthorizedError, ForbiddenError } from '@shared/errors/errors.js';
4
4
  import { isAppError } from '@shared/errors/AppError.js';
5
5
  import { setAuthCookies, clearAuthCookies } from '@libs/cookies.js';
6
6
  import { getClientIp } from '@libs/client-ip.js';
7
+ import type { JwtPayload } from '@shared/types/index.js';
7
8
  import type {
8
9
  RegisterInput,
9
10
  LoginInput,
@@ -79,10 +80,20 @@ export async function logout(
79
80
  request: FastifyRequest,
80
81
  reply: FastifyReply,
81
82
  ): Promise<void> {
82
- const refreshToken = request.cookies.refresh_token;
83
- if (refreshToken) {
84
- await authService.logout(refreshToken);
83
+ // Verify the cookie explicitly. Logout also accepts a refresh cookie when
84
+ // the access cookie has expired, and works as an idempotent anonymous call.
85
+ let accessSession: Pick<JwtPayload, 'userId' | 'sessionId'> | undefined;
86
+ if (request.cookies.access_token) {
87
+ try {
88
+ const { userId, sessionId } = request.server.jwt.verify<JwtPayload>(request.cookies.access_token);
89
+ if (typeof userId === 'string' && userId && typeof sessionId === 'string' && sessionId) {
90
+ accessSession = { userId, sessionId };
91
+ }
92
+ } catch {
93
+ // The refresh credential can still identify the session.
94
+ }
85
95
  }
96
+ await authService.logout(request.cookies.refresh_token, accessSession);
86
97
 
87
98
  clearAuthCookies(reply);
88
99
  reply.send(successResponse('Logged out successfully', null));
@@ -108,7 +119,7 @@ export async function logoutAllSessions(
108
119
  request: FastifyRequest,
109
120
  reply: FastifyReply,
110
121
  ): Promise<void> {
111
- const count = await authService.logoutAllSessions(request.user.userId);
122
+ const count = await authService.logoutAllSessions(request.user);
112
123
  clearAuthCookies(reply);
113
124
  reply.send(
114
125
  successResponse(`Successfully logged out from ${count} session(s)`, { count }),
@@ -120,7 +131,7 @@ export async function forgotPassword(
120
131
  reply: FastifyReply,
121
132
  ): Promise<void> {
122
133
  await authService.forgotPassword(request.body.email);
123
- // Always return success to prevent email enumeration
134
+ // The queue accepts work before the worker determines whether an account exists.
124
135
  reply.send(successResponse('If an account exists with that email, a reset link has been sent', null));
125
136
  }
126
137