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,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
 
@@ -1,6 +1,9 @@
1
1
  import { prisma, isPrismaNotFound, isPrismaWriteConflict } from '@libs/prisma.js';
2
2
  import { hashToken } from '@libs/token-hash.js';
3
- import type { User, RefreshToken } from '@prisma/client';
3
+ import { assertAccountCanSignIn } from '@libs/account-status.js';
4
+ import { assertMutationActor, revokeAccountCredentials, runAccountMutation, type MutationActor } from '@libs/account-mutation.js';
5
+ import type { JwtPayload } from '@shared/types/index.js';
6
+ import type { User, RefreshToken, Prisma, Session } from '@prisma/client';
4
7
 
5
8
  export async function findUserByEmail(email: string): Promise<User | null> {
6
9
  return prisma.user.findUnique({
@@ -42,8 +45,8 @@ export async function createRefreshToken(data: {
42
45
  userId: string;
43
46
  sessionId?: string;
44
47
  expiresAt: Date;
45
- }): Promise<RefreshToken> {
46
- return prisma.refreshToken.create({
48
+ }, db: Prisma.TransactionClient = prisma): Promise<RefreshToken> {
49
+ return db.refreshToken.create({
47
50
  data: { ...data, token: hashToken(data.token) },
48
51
  });
49
52
  }
@@ -65,71 +68,159 @@ export async function deleteRefreshToken(token: string): Promise<void> {
65
68
  }
66
69
  }
67
70
 
68
- /**
69
- * Atomically swap a refresh token for a new one AND move its session forward.
70
- *
71
- * The session row is what users (GET /auth/sessions) and admins see and
72
- * revoke, so it must stay in step with the token family: every rotation sets
73
- * the session's expiresAt to the new token's expiry and refreshes lastActiveAt.
74
- * Previously only the token's expiry slid forward, so after the first
75
- * JWT_REFRESH_EXPIRY window a still-used login vanished from session lists and
76
- * could no longer be force-expired.
77
- *
78
- * Exactly one of several parallel rotations of the same token wins. The old
79
- * row is removed with deleteMany, a locking DELETE whose count says whether
80
- * THIS transaction removed it: a parallel one waits for the row lock, then
81
- * removes nothing and returns false. (delete() checked the row in a snapshot
82
- * first, so under MySQL's REPEATABLE READ two parallel refreshes both "found"
83
- * it and both created a new token, forking the login; sometimes they
84
- * deadlocked instead and answered 500.)
85
- *
86
- * Returns false when this request did not win: the token was already rotated
87
- * by a parallel refresh, the session is gone, or MySQL reported a write
88
- * conflict with the parallel transaction. See refresh() in auth.service.ts.
89
- * Both tokens are passed raw and stored as fingerprints.
90
- */
71
+ type RefreshRotation =
72
+ | { kind: 'issued'; claims: JwtPayload }
73
+ | { kind: 'rotated' | 'invalid' | 'expired-token' | 'expired-session' };
74
+
75
+ async function retiredSession(
76
+ db: Prisma.TransactionClient, fingerprint: string,
77
+ ): Promise<MutationActor | null> {
78
+ const now = new Date();
79
+ const retired = await db.retiredRefreshToken.findFirst({
80
+ where: { fingerprint, expiresAt: { gt: now }, session: { expiresAt: { gt: now } } },
81
+ select: { sessionId: true, session: { select: { userId: true } } },
82
+ });
83
+ return retired ? { userId: retired.session.userId, sessionId: retired.sessionId } : null;
84
+ }
85
+
91
86
  export async function rotateRefreshToken(
92
- oldToken: string,
93
- newData: { token: string; userId: string; sessionId: string; expiresAt: Date },
94
- ): Promise<boolean> {
95
- try {
96
- return await prisma.$transaction(async (tx) => {
97
- const { count } = await tx.refreshToken.deleteMany({ where: { token: hashToken(oldToken) } });
98
- if (count !== 1) return false; // a parallel refresh rotated it first
99
- await tx.session.update({
100
- where: { id: newData.sessionId },
101
- data: { expiresAt: newData.expiresAt, lastActiveAt: new Date() },
102
- });
103
- await tx.refreshToken.create({ data: { ...newData, token: hashToken(newData.token) } });
104
- return true;
87
+ oldToken: string, newToken: string, getExpiry: (now: Date) => Date,
88
+ ): Promise<RefreshRotation> {
89
+ const fingerprint = hashToken(oldToken);
90
+ // This lookup only locates the user lock. The transaction reads current state
91
+ // again after locking so time spent waiting counts against both deadlines.
92
+ const candidate = await findRefreshToken(oldToken);
93
+ if (!candidate) return { kind: await retiredSession(prisma, fingerprint) ? 'rotated' : 'invalid' };
94
+
95
+ return runAccountMutation<RefreshRotation>(async tx => {
96
+ const user = await lockUser(tx, candidate.userId);
97
+ if (!user || user.deletedAt) return { kind: 'invalid' };
98
+ const stored = await tx.refreshToken.findUnique({ where: { token: fingerprint } });
99
+ if (!stored || stored.userId !== candidate.userId) {
100
+ return { kind: await retiredSession(tx, fingerprint) ? 'rotated' : 'invalid' };
101
+ }
102
+ const session = stored.sessionId ? await tx.session.findFirst({
103
+ where: { id: stored.sessionId, userId: stored.userId },
104
+ select: { id: true, expiresAt: true },
105
+ }) : null;
106
+ const now = new Date();
107
+ if (stored.expiresAt <= now) {
108
+ await tx.refreshToken.delete({ where: { id: stored.id } });
109
+ return { kind: 'expired-token' };
110
+ }
111
+ if (!session || session.expiresAt <= now) {
112
+ await tx.refreshToken.delete({ where: { id: stored.id } });
113
+ return { kind: 'expired-session' };
114
+ }
115
+ assertAccountCanSignIn(user);
116
+ const expiresAt = getExpiry(now);
117
+ await tx.refreshToken.delete({ where: { id: stored.id } });
118
+ await tx.session.update({ where: { id: session.id }, data: { expiresAt, lastActiveAt: now } });
119
+ await tx.refreshToken.create({
120
+ data: { token: hashToken(newToken), userId: stored.userId, sessionId: session.id, expiresAt },
105
121
  });
106
- } catch (error) {
107
- if (isPrismaNotFound(error) || isPrismaWriteConflict(error)) return false;
108
- throw error;
122
+ // This proof is published only if the new token commits. A retired
123
+ // fingerprint can be used to end its session for sixty seconds.
124
+ await tx.retiredRefreshToken.create({
125
+ data: { fingerprint, sessionId: session.id, expiresAt: new Date(now.getTime() + 60_000) },
126
+ });
127
+ return { kind: 'issued', claims: { userId: stored.userId, sessionId: session.id, role: user.role } };
128
+ });
129
+ }
130
+
131
+ export async function revokeSession(refreshToken?: string, accessSession?: MutationActor): Promise<void> {
132
+ const fingerprint = refreshToken ? hashToken(refreshToken) : undefined;
133
+ let userId = accessSession?.userId;
134
+ if (!userId && fingerprint) {
135
+ const current = await prisma.refreshToken.findUnique({ where: { token: fingerprint } });
136
+ userId = current?.userId ?? (await retiredSession(prisma, fingerprint))?.userId;
109
137
  }
138
+ if (!userId) return;
139
+ const owner = userId;
140
+ await runAccountMutation(async tx => {
141
+ if (!await lockUser(tx, owner)) return;
142
+ if (accessSession) {
143
+ // A verified access cookie names exactly one session, even if another
144
+ // browser cookie belongs to a different session.
145
+ await tx.session.deleteMany({ where: { id: accessSession.sessionId, userId: owner } });
146
+ return;
147
+ }
148
+ if (!fingerprint) return;
149
+ const current = await tx.refreshToken.findUnique({ where: { token: fingerprint } });
150
+ if (current?.userId === owner && !current.sessionId) {
151
+ // Credentials from before session tracking have no session to cascade.
152
+ await tx.refreshToken.deleteMany({ where: { token: fingerprint, userId: owner, sessionId: null } });
153
+ return;
154
+ }
155
+ const retired = current ? null : await retiredSession(tx, fingerprint);
156
+ const sessionId = current?.userId === owner ? current.sessionId : retired?.userId === owner ? retired.sessionId : null;
157
+ if (sessionId) await tx.session.deleteMany({ where: { id: sessionId, userId: owner } });
158
+ });
110
159
  }
111
160
 
112
- /**
113
- * Delete a user's refresh tokens; with `exceptSessionId`, keep that one
114
- * session's tokens (an owner's password change keeps the asking device signed
115
- * in). Tokens without a session are always deleted: the explicit `sessionId:
116
- * null` branch is needed because SQL `sessionId <> x` skips NULL rows.
117
- */
118
- export async function deleteRefreshTokensByUserId(
119
- userId: string,
120
- options: { exceptSessionId?: string } = {},
121
- ): Promise<void> {
122
- const { exceptSessionId } = options;
123
- await prisma.refreshToken.deleteMany({
124
- where: exceptSessionId
125
- ? { userId, OR: [{ sessionId: null }, { sessionId: { not: exceptSessionId } }] }
126
- : { userId },
161
+ export function revokeAllSessions(actor: MutationActor): Promise<number> {
162
+ return runAccountMutation(async tx => {
163
+ await lockUser(tx, actor.userId);
164
+ await assertMutationActor(tx, actor);
165
+ return revokeAccountCredentials(tx, actor.userId);
127
166
  });
128
167
  }
129
168
 
130
- export async function updateUserPassword(userId: string, hashedPassword: string): Promise<void> {
131
- await prisma.user.update({
132
- where: { id: userId },
133
- data: { password: hashedPassword },
169
+ // Sign-in, refresh and recovery acquire locks in user → session/token order.
170
+ // Read the current row under the lock, not a transaction snapshot.
171
+ type LockedUser = Pick<User, 'password' | 'isActive' | 'emailVerifiedAt' | 'deletedAt' | 'role'>;
172
+
173
+ export async function lockUser(tx: Prisma.TransactionClient, userId: string): Promise<LockedUser | undefined> {
174
+ const [user] = await tx.$queryRaw<LockedUser[]>`
175
+ SELECT password, isActive, emailVerifiedAt, deletedAt, role FROM users WHERE id = ${userId} FOR UPDATE
176
+ `;
177
+ return user;
178
+ }
179
+
180
+ export async function createLoginSession(input: {
181
+ userId: string;
182
+ verifiedPasswordHash: string;
183
+ refreshToken: string;
184
+ expiresAt: Date;
185
+ deviceInfo?: string;
186
+ ipAddress?: string;
187
+ }): Promise<Session | null> {
188
+ return prisma.$transaction(async tx => {
189
+ const user = await lockUser(tx, input.userId);
190
+ if (!user || user.deletedAt || user.password !== input.verifiedPasswordHash) return null;
191
+ assertAccountCanSignIn(user);
192
+ const session = await tx.session.create({
193
+ data: {
194
+ userId: input.userId, deviceInfo: input.deviceInfo, ipAddress: input.ipAddress,
195
+ expiresAt: input.expiresAt,
196
+ },
197
+ });
198
+ await tx.refreshToken.create({
199
+ data: {
200
+ userId: input.userId, sessionId: session.id, expiresAt: input.expiresAt,
201
+ token: hashToken(input.refreshToken),
202
+ },
203
+ });
204
+ return session;
134
205
  });
135
206
  }
207
+
208
+ export async function commitPasswordRecovery(
209
+ userId: string, expectedHash: string, replacementHash: string,
210
+ ): Promise<boolean> {
211
+ for (let attempt = 1; ; attempt++) {
212
+ try {
213
+ return await prisma.$transaction(async tx => {
214
+ const user = await lockUser(tx, userId);
215
+ if (!user || user.deletedAt || user.password !== expectedHash) return false;
216
+ await tx.user.update({ where: { id: userId }, data: { password: replacementHash } });
217
+ await tx.session.deleteMany({ where: { userId } });
218
+ // Cascades handle session-bound rows. Older records may have no session.
219
+ await tx.refreshToken.deleteMany({ where: { userId } });
220
+ return true;
221
+ });
222
+ } catch (error) {
223
+ if (attempt >= 3 || !isPrismaWriteConflict(error)) throw error;
224
+ }
225
+ }
226
+ }
@@ -1,5 +1,6 @@
1
1
  import type { FastifyInstance } from 'fastify';
2
2
  import { authenticate } from '@libs/auth.js';
3
+ import { preventPrivateCaching } from '@libs/private-cache.js';
3
4
  import { RATE_LIMITS } from '@config/rate-limit.config.js';
4
5
  import * as authController from './auth.controller.js';
5
6
  import {
@@ -10,6 +11,9 @@ import {
10
11
  } from './auth.schemas.js';
11
12
 
12
13
  export async function authRoutes(fastify: FastifyInstance): Promise<void> {
14
+ // Protect public sign-in responses too, including validation and credential errors.
15
+ fastify.addHook('onRequest', async (_request, reply) => preventPrivateCaching(reply));
16
+
13
17
  // Register - Strict rate limiting to prevent abuse
14
18
  fastify.post('/auth/register', {
15
19
  schema: {
@@ -1,7 +1,11 @@
1
1
  import { z } from 'zod';
2
2
 
3
+ // Prisma's MySQL User.email column is VARCHAR(191). Apply its boundary
4
+ // before password hashing or database access on account writes and sign-in.
5
+ const accountEmail = z.string().max(191, 'Email address is too long').email('Invalid email address').toLowerCase().trim();
6
+
3
7
  export const registerSchema = z.object({
4
- email: z.string().email('Invalid email address').toLowerCase().trim(),
8
+ email: accountEmail,
5
9
  password: z
6
10
  .string()
7
11
  .min(8, 'Password must be at least 8 characters')
@@ -16,7 +20,7 @@ export const registerSchema = z.object({
16
20
  });
17
21
 
18
22
  export const loginSchema = z.object({
19
- email: z.string().email('Invalid email address').toLowerCase().trim(),
23
+ email: accountEmail,
20
24
  password: z.string().min(1, 'Password is required'),
21
25
  });
22
26
 
@@ -24,7 +28,7 @@ export type RegisterInput = z.infer<typeof registerSchema>;
24
28
  export type LoginInput = z.infer<typeof loginSchema>;
25
29
 
26
30
  export const forgotPasswordSchema = z.object({
27
- email: z.string().email('Invalid email address').toLowerCase().trim(),
31
+ email: z.string().max(254).email('Invalid email address').toLowerCase().trim(),
28
32
  });
29
33
 
30
34
  export const resetPasswordSchema = z.object({