create-tigra 4.1.0 → 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 (140) hide show
  1. package/CHANGELOG.md +16 -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/src/features/auth/components/AuthInitializer.tsx +45 -7
  31. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  32. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  33. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  34. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  35. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  36. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  37. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  38. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  39. package/template/client/src/lib/api/axios.config.ts +24 -6
  40. package/template/client/src/lib/api/session-events.ts +54 -0
  41. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  42. package/template/client/src/store/__tests__/store.test.ts +1 -0
  43. package/template/gitignore +3 -2
  44. package/template/server/.dockerignore +2 -5
  45. package/template/server/.env.example +1 -0
  46. package/template/server/.env.example.production +1 -0
  47. package/template/server/README.md +7 -2
  48. package/template/server/docs/deployment.md +66 -0
  49. package/template/server/docs/logging.md +9 -8
  50. package/template/server/docs/rate-limits.md +6 -4
  51. package/template/server/gitignore +33 -0
  52. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  53. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  54. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  55. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  56. package/template/server/prisma/schema.prisma +25 -1
  57. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  58. package/template/server/src/app.ts +14 -5
  59. package/template/server/src/config/env.ts +8 -0
  60. package/template/server/src/config/rate-limit.config.ts +1 -1
  61. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  62. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  63. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  64. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  65. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  66. package/template/server/src/jobs/index.ts +8 -2
  67. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  68. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  69. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  70. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  71. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  72. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  73. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  74. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  75. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  76. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  77. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  78. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  79. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  80. package/template/server/src/libs/account-mutation.ts +77 -0
  81. package/template/server/src/libs/auth.ts +37 -3
  82. package/template/server/src/libs/cookies.ts +25 -13
  83. package/template/server/src/libs/email-quota.ts +11 -7
  84. package/template/server/src/libs/email.ts +11 -8
  85. package/template/server/src/libs/error-handler.ts +16 -12
  86. package/template/server/src/libs/http.ts +37 -13
  87. package/template/server/src/libs/ip-block.ts +56 -34
  88. package/template/server/src/libs/logger.ts +23 -8
  89. package/template/server/src/libs/monitoring.ts +57 -31
  90. package/template/server/src/libs/observability/sentry.ts +65 -49
  91. package/template/server/src/libs/prisma.ts +1 -1
  92. package/template/server/src/libs/private-cache.ts +6 -0
  93. package/template/server/src/libs/rate-limiting.ts +4 -0
  94. package/template/server/src/libs/requestLogger.ts +3 -3
  95. package/template/server/src/libs/safe-http.ts +58 -18
  96. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  97. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  98. package/template/server/src/libs/storage/file-validator.ts +2 -1
  99. package/template/server/src/libs/url-safety.ts +10 -2
  100. package/template/server/src/libs/validation-errors.ts +11 -8
  101. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  102. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  103. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  104. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  105. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  106. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  107. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  108. package/template/server/src/modules/admin/admin.service.ts +61 -62
  109. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  110. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  111. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  112. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  113. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  114. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  115. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  116. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  117. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  118. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  119. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  120. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  121. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  122. package/template/server/src/modules/auth/auth.service.ts +33 -237
  123. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  124. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  125. package/template/server/src/modules/auth/session.repo.ts +5 -4
  126. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  127. package/template/server/src/modules/files/files.controller.ts +2 -2
  128. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  129. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  130. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  131. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  132. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  133. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  134. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  135. package/template/server/src/modules/users/users.controller.ts +28 -25
  136. package/template/server/src/modules/users/users.repo.ts +12 -51
  137. package/template/server/src/modules/users/users.service.ts +109 -234
  138. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  139. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  140. package/template/server/src/test/setup.ts +4 -0
@@ -0,0 +1,177 @@
1
+ import { afterAll, beforeAll, expect, it } from 'vitest';
2
+ import type { FastifyInstance } from 'fastify';
3
+ import { createHash } from 'node:crypto';
4
+ import { buildTestApp, db, PASSWORD, redis, startEmailStub, tokenOf, uniqueEmail, type EmailStub } from '@/test/integration-helpers.js';
5
+
6
+ let app: FastifyInstance;
7
+ let mail: EmailStub;
8
+ let origin: string;
9
+ const client = 'https://recovery-client.example.test';
10
+ const newPassword = 'New-Fixture-Passw0rd-42';
11
+ const verification = process.env.TIGRA_LIVE_VERIFICATION === 'true';
12
+ const fingerprint = (token: string): string => createHash('sha256').update(token).digest('hex');
13
+
14
+ interface AuthResponse {
15
+ status: number;
16
+ data: { data?: { user?: { id: string }; id?: string }; error?: { code: string } };
17
+ cookies: string;
18
+ }
19
+
20
+ beforeAll(async () => {
21
+ process.env.CLIENT_URL = client;
22
+ process.env.REQUIRE_USER_VERIFICATION = String(verification);
23
+ process.env.RATE_LIMIT_ENABLED = 'true';
24
+ mail = await startEmailStub();
25
+ app = await buildTestApp();
26
+ origin = await app.listen({ host: '127.0.0.1', port: 0 });
27
+ });
28
+
29
+ afterAll(async () => {
30
+ await app?.close();
31
+ await mail?.close();
32
+ });
33
+
34
+ async function request(route: string, body?: object, cookie?: string): Promise<AuthResponse> {
35
+ const response = await fetch(`${origin}/api/v1/auth/${route}`, {
36
+ method: body === undefined ? 'GET' : 'POST',
37
+ headers: {
38
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
39
+ ...(cookie ? { cookie } : {}),
40
+ },
41
+ body: body === undefined ? undefined : JSON.stringify(body),
42
+ });
43
+ const data = await response.json() as AuthResponse['data'];
44
+ const cookies = response.headers.getSetCookie().map(value => value.split(';', 1)[0]).join('; ');
45
+ return { status: response.status, data, cookies };
46
+ }
47
+
48
+ async function register(tag: string): Promise<{ email: string; cookies: string; id?: string }> {
49
+ const email = uniqueEmail(tag);
50
+ const registration = await request('register', { email, password: PASSWORD, firstName: 'Test', lastName: 'User' });
51
+ expect(registration.status).toBe(201);
52
+ if (!verification) return { email, cookies: registration.cookies, id: registration.data.data?.user?.id };
53
+ const inbox = await mail.waitFor(email, entry => Boolean(entry.link?.includes('/verify-account')));
54
+ const result = await request('verify-account', { token: tokenOf(inbox[0]?.link ?? null) });
55
+ expect(result.status).toBe(200);
56
+ return { email, cookies: result.cookies, id: registration.data.data?.user?.id };
57
+ }
58
+
59
+ const isResetMail = (entry: { link: string | null }): boolean => Boolean(entry.link?.includes('/reset-password'));
60
+
61
+ async function resetMail(email: string, count: number): Promise<string> {
62
+ const messages = await mail.waitFor(email, isResetMail, count);
63
+ expect(messages.length).toBe(count);
64
+ const message = messages.at(-1)!;
65
+ expect(message.to).toBe(email);
66
+ const url = new URL(message.link!);
67
+ expect(url.origin).toBe(client);
68
+ expect(url.pathname).toBe('/reset-password');
69
+ return tokenOf(url.href);
70
+ }
71
+
72
+ it('keeps recovery scoped to the recipient and invalidates old credentials after commit', async () => {
73
+ const account = await register('recover');
74
+ const other = await register('unrelated');
75
+ const secondLogin = await request('login', { email: account.email, password: PASSWORD });
76
+ expect(secondLogin.status).toBe(200);
77
+ expect((await request('forgot-password', { email: account.email })).status).toBe(200);
78
+ const first = await resetMail(account.email, 1);
79
+ expect((await request('forgot-password', { email: account.email })).status).toBe(200);
80
+ const latest = await resetMail(account.email, 2);
81
+ const cache = await redis();
82
+ expect(await cache.exists('pw-reset:' + fingerprint(first))).toBe(0);
83
+ expect(await cache.ttl('pw-reset:' + fingerprint(latest))).toBeGreaterThan(3_580);
84
+ expect((await request('reset-password', { token: first, newPassword })).status).toBe(400);
85
+
86
+ // Refresh rows from before session tracking have no session to cascade from.
87
+ const database = await db();
88
+ const legacy = await database.refreshToken.create({
89
+ data: {
90
+ token: fingerprint(uniqueEmail('legacy-refresh')),
91
+ userId: account.id!,
92
+ expiresAt: new Date(Date.now() + 60_000),
93
+ },
94
+ });
95
+ const results = await Promise.all([
96
+ request('reset-password', { token: latest, newPassword }),
97
+ request('reset-password', { token: latest, newPassword }),
98
+ ]);
99
+ expect(results.map(result => result.status).sort()).toEqual([200, 400]);
100
+ expect(await database.refreshToken.findUnique({ where: { id: legacy.id } })).toBeNull();
101
+ expect((await request('reset-password', { token: latest, newPassword })).status).toBe(400);
102
+ expect((await request('me', undefined, account.cookies)).status).toBe(401);
103
+ expect((await request('refresh', {}, secondLogin.cookies)).status).toBe(401);
104
+ expect((await request('login', { email: account.email, password: PASSWORD })).status).toBe(401);
105
+ const recovered = await request('login', { email: account.email, password: newPassword });
106
+ expect(recovered.data.data?.user?.id).toBe(account.id);
107
+ expect((await request('me', undefined, other.cookies)).data.data?.id).toBe(other.id);
108
+ });
109
+
110
+ it('rejects an expired recovery record', async () => {
111
+ const account = await register('expiry');
112
+ expect((await request('forgot-password', { email: account.email })).status).toBe(200);
113
+ const token = await resetMail(account.email, 1);
114
+ const cache = await redis();
115
+ await cache.pexpire('pw-reset:' + fingerprint(token), 1);
116
+ await expect.poll(() => cache.exists('pw-reset:' + fingerprint(token))).toBe(0);
117
+ const result = await request('reset-password', { token, newPassword });
118
+ expect([result.status, result.data.error?.code]).toEqual([400, 'INVALID_RESET_TOKEN']);
119
+ });
120
+
121
+ it('honors a current link issued before the upgrade', async () => {
122
+ const account = await register('legacy');
123
+ // The pre-upgrade store held a fingerprint-to-user entry and a matching pointer.
124
+ const token = 'legacy-reset-fixture';
125
+ const key = fingerprint(token);
126
+ const cache = await redis();
127
+ await cache.set('pw-reset:' + key, account.id!, 'EX', 60);
128
+ await cache.set('pw-reset-user:' + account.id, key, 'EX', 60);
129
+ const result = await request('reset-password', { token, newPassword });
130
+ expect(result.status).toBe(200);
131
+ expect(await cache.exists('pw-reset:' + key, 'pw-reset-user:' + account.id)).toBe(0);
132
+ });
133
+
134
+ it('keeps a later issuance current when older work resumes', async () => {
135
+ const { issueRecoveryToken } = await import('../recovery.store.js');
136
+ const account = await register('ordering');
137
+ const latest = 'latest-test-fixture';
138
+ const userId = account.id!;
139
+ await expect(issueRecoveryToken(userId, latest, '200-0')).resolves.toBe(true);
140
+ await expect(issueRecoveryToken(userId, 'older-test-fixture', '150-2')).resolves.toBe(false);
141
+ expect(await (await redis()).get('pw-reset-user:' + userId)).toBe(fingerprint(latest));
142
+ expect((await request('reset-password', { token: latest, newPassword })).status).toBe(200);
143
+ await expect(issueRecoveryToken(userId, latest, '200-0')).resolves.toBe(false);
144
+ });
145
+
146
+ it('shares quota across address casing and keeps the original registration', async () => {
147
+ const account = await register('quota');
148
+ const duplicate = await request('register', {
149
+ email: account.email.toUpperCase(), password: newPassword, firstName: 'Test', lastName: 'User',
150
+ });
151
+ expect(duplicate.status).toBe(409);
152
+ expect((await request('login', { email: account.email, password: PASSWORD })).data.data?.user?.id).toBe(account.id);
153
+ for (const email of [account.email, account.email.toUpperCase(), account.email]) {
154
+ expect((await request('forgot-password', { email })).status).toBe(200);
155
+ }
156
+ const refused = await request('forgot-password', { email: account.email.toUpperCase() });
157
+ expect([refused.status, refused.data.error?.code]).toEqual([429, 'EMAIL_RATE_LIMITED']);
158
+ await resetMail(account.email, 3);
159
+ });
160
+
161
+ it('acknowledges known and unknown recovery before a slow local provider responds', async () => {
162
+ const account = await register('slow-mail');
163
+ const unknown = uniqueEmail('unknown');
164
+ mail.respond({ delayMs: 3_000 });
165
+ const started = performance.now();
166
+ const [known, absent] = await Promise.all([
167
+ request('forgot-password', { email: account.email }),
168
+ request('forgot-password', { email: unknown }),
169
+ ]);
170
+ expect(performance.now() - started).toBeLessThan(2_000);
171
+ expect(known.status).toBe(200);
172
+ expect(absent.status).toBe(200);
173
+ expect(known.data).toEqual(absent.data);
174
+ await resetMail(account.email, 1);
175
+ expect(mail.to(unknown)).toHaveLength(0);
176
+ mail.respond({});
177
+ });
@@ -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
+ }