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.
- package/CHANGELOG.md +20 -0
- package/README.md +4 -1
- package/bin/create-tigra.js +68 -73
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +33 -59
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +18 -18
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +10 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +1 -24
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
- package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
- package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
- package/modules/metrics/performance.md +2 -2
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
- package/modules/metrics/server/metrics.collector.ts +6 -3
- package/modules/metrics/server/metrics.routes.ts +1 -2
- package/modules/metrics/server/metrics.service.ts +6 -2
- package/package.json +1 -1
- package/template/AGENTS.md +4 -3
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/package-lock.json +51 -51
- package/template/client/package.json +2 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -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
|
|
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
|
|
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
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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:
|
|
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:
|
|
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({
|
|
@@ -2,7 +2,7 @@ import crypto from 'node:crypto';
|
|
|
2
2
|
import { signAccessToken, generateRefreshToken, getRefreshTokenExpiresAt } from '@libs/auth.js';
|
|
3
3
|
import { hashPassword, verifyPassword } from '@libs/password.js';
|
|
4
4
|
import { getRedis } from '@libs/redis.js';
|
|
5
|
-
import {
|
|
5
|
+
import { enqueueRecovery } from './recovery.queue.js';
|
|
6
6
|
import { logger } from '@libs/logger.js';
|
|
7
7
|
import { env } from '@config/env.js';
|
|
8
8
|
import { assertAccountCanSignIn } from '@libs/account-status.js';
|
|
@@ -14,10 +14,10 @@ import {
|
|
|
14
14
|
TooManyRequestsError,
|
|
15
15
|
describeWait,
|
|
16
16
|
} from '@shared/errors/errors.js';
|
|
17
|
-
import {
|
|
17
|
+
import { consumeRecoveryToken, findRecoveryOwner } from './recovery.store.js';
|
|
18
18
|
import { assertRedisReady } from '@libs/redis-required.js';
|
|
19
|
-
import { hashToken } from '@libs/token-hash.js';
|
|
20
19
|
import type { UserRole } from '@shared/types/index.js';
|
|
20
|
+
import type { MutationActor } from '@libs/account-mutation.js';
|
|
21
21
|
import * as authRepo from './auth.repo.js';
|
|
22
22
|
import { sessionRepository } from './session.repo.js';
|
|
23
23
|
import type { RegisterInput, LoginInput } from './auth.schemas.js';
|
|
@@ -25,37 +25,6 @@ import type { RegisterInput, LoginInput } from './auth.schemas.js';
|
|
|
25
25
|
/** A refresh that lost a race with a parallel one (see refresh()); its cookies must stay. */
|
|
26
26
|
export const REFRESH_TOKEN_ROTATED = 'REFRESH_TOKEN_ROTATED';
|
|
27
27
|
|
|
28
|
-
// "Just rotated" notes: `rt-rotated:<sha256 of the old refresh token>`, kept
|
|
29
|
-
// for a minute. A parallel refresh that arrives a few ms after the winner
|
|
30
|
-
// finds its token already gone; the note tells it apart from a stale or
|
|
31
|
-
// stolen token, so it gets REFRESH_TOKEN_ROTATED (cookies kept) instead of
|
|
32
|
-
// INVALID_REFRESH_TOKEN (cookies cleared, signing that browser out).
|
|
33
|
-
const ROTATED_NOTE_PREFIX = 'rt-rotated:';
|
|
34
|
-
const ROTATED_NOTE_SECONDS = 60;
|
|
35
|
-
|
|
36
|
-
async function noteRotation(refreshToken: string): Promise<void> {
|
|
37
|
-
try {
|
|
38
|
-
await getRedis().set(`${ROTATED_NOTE_PREFIX}${hashToken(refreshToken)}`, '1', 'EX', ROTATED_NOTE_SECONDS);
|
|
39
|
-
} catch {
|
|
40
|
-
// Redis down: a late parallel refresh then falls back to INVALID_REFRESH_TOKEN
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async function wasJustRotated(refreshToken: string): Promise<boolean> {
|
|
45
|
-
try {
|
|
46
|
-
return (await getRedis().exists(`${ROTATED_NOTE_PREFIX}${hashToken(refreshToken)}`)) === 1;
|
|
47
|
-
} catch {
|
|
48
|
-
return false;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const PASSWORD_RESET_TTL = 3600; // 1 hour in seconds
|
|
53
|
-
// Reset tokens in Redis are stored by fingerprint only (libs/token-hash.ts):
|
|
54
|
-
// `pw-reset:<sha256>` -> userId, and `pw-reset-user:<userId>` -> that sha256
|
|
55
|
-
// (to invalidate a user's previous link). The raw token exists only in the email.
|
|
56
|
-
const PASSWORD_RESET_PREFIX = 'pw-reset:';
|
|
57
|
-
const PASSWORD_RESET_USER_PREFIX = 'pw-reset-user:';
|
|
58
|
-
|
|
59
28
|
// --- Account lockout (scoped to email + IP) ---
|
|
60
29
|
// Failed-login attempts are tracked in Redis keyed by the (email, IP) PAIR.
|
|
61
30
|
// Keying by email alone let anyone lock a victim out remotely by spamming bad
|
|
@@ -315,29 +284,18 @@ export async function login(
|
|
|
315
284
|
// caller cannot learn whether an email is banned or unverified.
|
|
316
285
|
assertAccountCanSignIn(user);
|
|
317
286
|
|
|
318
|
-
//
|
|
287
|
+
// Login rechecks the verified hash under the same lock used by recovery.
|
|
319
288
|
const refreshToken = generateRefreshToken();
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
const session = await sessionRepository.createSession({
|
|
289
|
+
const session = await authRepo.createLoginSession({
|
|
323
290
|
userId: user.id,
|
|
291
|
+
verifiedPasswordHash: user.password,
|
|
292
|
+
refreshToken,
|
|
324
293
|
deviceInfo,
|
|
325
294
|
ipAddress,
|
|
326
|
-
expiresAt:
|
|
327
|
-
});
|
|
328
|
-
|
|
329
|
-
const accessToken = signAccessToken({
|
|
330
|
-
userId: user.id,
|
|
331
|
-
role: user.role,
|
|
332
|
-
sessionId: session.id,
|
|
333
|
-
});
|
|
334
|
-
|
|
335
|
-
await authRepo.createRefreshToken({
|
|
336
|
-
token: refreshToken,
|
|
337
|
-
userId: user.id,
|
|
338
|
-
sessionId: session.id,
|
|
339
|
-
expiresAt: refreshTokenExpiresAt,
|
|
295
|
+
expiresAt: getRefreshTokenExpiresAt(),
|
|
340
296
|
});
|
|
297
|
+
if (!session) throw new UnauthorizedError('Invalid email or password', 'INVALID_CREDENTIALS');
|
|
298
|
+
const accessToken = signAccessToken({ userId: user.id, role: user.role, sessionId: session.id });
|
|
341
299
|
|
|
342
300
|
return {
|
|
343
301
|
user: sanitizeUser(user),
|
|
@@ -347,90 +305,22 @@ export async function login(
|
|
|
347
305
|
}
|
|
348
306
|
|
|
349
307
|
export async function refresh(refreshToken: string): Promise<{ accessToken: string; refreshToken: string }> {
|
|
350
|
-
const storedToken = await authRepo.findRefreshToken(refreshToken);
|
|
351
|
-
if (!storedToken) {
|
|
352
|
-
// Gone a moment ago because a parallel refresh rotated it: lost race, not a bad token.
|
|
353
|
-
if (await wasJustRotated(refreshToken)) {
|
|
354
|
-
throw new UnauthorizedError('Refresh token already used by a parallel request', REFRESH_TOKEN_ROTATED);
|
|
355
|
-
}
|
|
356
|
-
throw new UnauthorizedError('Invalid refresh token', 'INVALID_REFRESH_TOKEN');
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
if (new Date() > storedToken.expiresAt) {
|
|
360
|
-
await authRepo.deleteRefreshToken(refreshToken);
|
|
361
|
-
throw new UnauthorizedError('Refresh token expired', 'REFRESH_TOKEN_EXPIRED');
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// A token is only as alive as its session. If the session row is gone
|
|
365
|
-
// (logout elsewhere, admin force-expire, cleanup job) or past its expiry, the
|
|
366
|
-
// login is over: drop the token instead of minting new ones.
|
|
367
|
-
const session = storedToken.sessionId
|
|
368
|
-
? await sessionRepository.getSessionById(storedToken.sessionId)
|
|
369
|
-
: null;
|
|
370
|
-
if (!session || session.expiresAt <= new Date()) {
|
|
371
|
-
await authRepo.deleteRefreshToken(refreshToken);
|
|
372
|
-
throw new UnauthorizedError('Session expired', 'SESSION_EXPIRED');
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
const user = await authRepo.findUserById(storedToken.userId);
|
|
376
|
-
if (!user) {
|
|
377
|
-
throw new UnauthorizedError('User not found or disabled', 'INVALID_REFRESH_TOKEN');
|
|
378
|
-
}
|
|
379
|
-
// A ban (or a pending verification) also stops refresh, so a banned user's
|
|
380
|
-
// leftover refresh token cannot mint new access tokens.
|
|
381
|
-
assertAccountCanSignIn(user);
|
|
382
|
-
|
|
383
|
-
const newAccessToken = signAccessToken({
|
|
384
|
-
userId: user.id,
|
|
385
|
-
role: user.role,
|
|
386
|
-
sessionId: session.id,
|
|
387
|
-
});
|
|
388
308
|
const newRefreshToken = generateRefreshToken();
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
// lost race. Harmless if this rotation then fails: the note only matters to
|
|
393
|
-
// requests whose token no longer exists.
|
|
394
|
-
await noteRotation(refreshToken);
|
|
395
|
-
|
|
396
|
-
// Single-winner rotation (see rotateRefreshToken): false when a parallel
|
|
397
|
-
// request rotated this token first.
|
|
398
|
-
const rotated = await authRepo.rotateRefreshToken(refreshToken, {
|
|
399
|
-
token: newRefreshToken,
|
|
400
|
-
userId: user.id,
|
|
401
|
-
sessionId: session.id,
|
|
402
|
-
expiresAt: getRefreshTokenExpiresAt(),
|
|
403
|
-
});
|
|
404
|
-
|
|
405
|
-
if (!rotated) {
|
|
406
|
-
// A parallel request rotated this token first. That is normally two tabs
|
|
407
|
-
// of the same browser refreshing at once (they share the cookie and the
|
|
408
|
-
// 15-minute access token, so both refresh when it expires). The winner's
|
|
409
|
-
// response has already set the new cookies, so refuse ONLY this request,
|
|
410
|
-
// with a code the controller recognises so it does NOT clear those cookies.
|
|
411
|
-
// Nothing is revoked: wiping every session here used to sign the user out
|
|
412
|
-
// on all devices for a harmless race, while a real replay of a stolen old
|
|
413
|
-
// token arrives later and is rejected above as not found.
|
|
414
|
-
logger.info({ userId: user.id }, '[AUTH] Parallel refresh lost the race; refusing only this request');
|
|
415
|
-
throw new UnauthorizedError('Refresh token already used by a parallel request', REFRESH_TOKEN_ROTATED);
|
|
309
|
+
const result = await authRepo.rotateRefreshToken(refreshToken, newRefreshToken, getRefreshTokenExpiresAt);
|
|
310
|
+
if (result.kind === 'issued') {
|
|
311
|
+
return { accessToken: signAccessToken(result.claims), refreshToken: newRefreshToken };
|
|
416
312
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
313
|
+
const [message, code] = {
|
|
314
|
+
rotated: ['Refresh token already used by a parallel request', REFRESH_TOKEN_ROTATED],
|
|
315
|
+
invalid: ['Invalid refresh token', 'INVALID_REFRESH_TOKEN'],
|
|
316
|
+
'expired-token': ['Refresh token expired', 'REFRESH_TOKEN_EXPIRED'],
|
|
317
|
+
'expired-session': ['Session expired', 'SESSION_EXPIRED'],
|
|
318
|
+
}[result.kind];
|
|
319
|
+
throw new UnauthorizedError(message, code);
|
|
422
320
|
}
|
|
423
321
|
|
|
424
|
-
export
|
|
425
|
-
|
|
426
|
-
// Both deleteRefreshToken and deleteSession handle "already deleted" (P2025)
|
|
427
|
-
// gracefully, so no catch needed for concurrent request / cleanup job races.
|
|
428
|
-
const storedToken = await authRepo.findRefreshToken(refreshToken);
|
|
429
|
-
await authRepo.deleteRefreshToken(refreshToken);
|
|
430
|
-
|
|
431
|
-
if (storedToken?.sessionId) {
|
|
432
|
-
await sessionRepository.deleteSession(storedToken.sessionId);
|
|
433
|
-
}
|
|
322
|
+
export function logout(refreshToken?: string, accessSession?: MutationActor): Promise<void> {
|
|
323
|
+
return authRepo.revokeSession(refreshToken, accessSession);
|
|
434
324
|
}
|
|
435
325
|
|
|
436
326
|
export async function getCurrentUser(userId: string): Promise<SanitizedUser> {
|
|
@@ -463,121 +353,27 @@ export async function getUserSessions(userId: string): Promise<SessionInfo[]> {
|
|
|
463
353
|
}));
|
|
464
354
|
}
|
|
465
355
|
|
|
466
|
-
export
|
|
467
|
-
|
|
468
|
-
await authRepo.deleteRefreshTokensByUserId(userId);
|
|
469
|
-
return sessionCount;
|
|
356
|
+
export function logoutAllSessions(actor: MutationActor): Promise<number> {
|
|
357
|
+
return authRepo.revokeAllSessions(actor);
|
|
470
358
|
}
|
|
471
359
|
|
|
472
360
|
export async function forgotPassword(email: string): Promise<void> {
|
|
473
|
-
// Reset tokens live in Redis: without it, answer a clear 503 for every
|
|
474
|
-
// address (checked before the lookup, so it reveals nothing).
|
|
475
361
|
assertRedisReady('Password reset');
|
|
476
|
-
|
|
477
|
-
// Per-address email cap, counted BEFORE the lookup so unknown addresses are
|
|
478
|
-
// counted too (the 429 reveals nothing about the account). See libs/email-quota.ts.
|
|
479
|
-
await consumeEmailQuota(email);
|
|
480
|
-
|
|
481
|
-
const user = await authRepo.findUserByEmail(email);
|
|
482
|
-
|
|
483
|
-
// Silent return if user not found — prevents email enumeration
|
|
484
|
-
if (!user) return;
|
|
485
|
-
|
|
486
|
-
const redis = getRedis();
|
|
487
|
-
|
|
488
|
-
// Invalidate any existing token for this user (the pointer holds its fingerprint)
|
|
489
|
-
const existingTokenHash = await redis.get(`${PASSWORD_RESET_USER_PREFIX}${user.id}`);
|
|
490
|
-
if (existingTokenHash) {
|
|
491
|
-
await redis.del(`${PASSWORD_RESET_PREFIX}${existingTokenHash}`);
|
|
492
|
-
await redis.del(`${PASSWORD_RESET_USER_PREFIX}${user.id}`);
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
// Generate a secure token; only its fingerprint goes to Redis (1 hour TTL)
|
|
496
|
-
const token = crypto.randomBytes(32).toString('hex');
|
|
497
|
-
const tokenHash = hashToken(token);
|
|
498
|
-
|
|
499
|
-
await redis.set(`${PASSWORD_RESET_PREFIX}${tokenHash}`, user.id, 'EX', PASSWORD_RESET_TTL);
|
|
500
|
-
await redis.set(`${PASSWORD_RESET_USER_PREFIX}${user.id}`, tokenHash, 'EX', PASSWORD_RESET_TTL);
|
|
501
|
-
|
|
502
|
-
// Build reset URL and send email
|
|
503
|
-
const resetUrl = `${env.CLIENT_URL}/reset-password?token=${token}`;
|
|
504
|
-
const safeName = user.firstName.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
505
|
-
|
|
506
|
-
try {
|
|
507
|
-
await sendEmail({
|
|
508
|
-
to: user.email,
|
|
509
|
-
subject: 'Reset your password',
|
|
510
|
-
html: `
|
|
511
|
-
<table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f3ee; padding: 40px 20px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
|
|
512
|
-
<tr>
|
|
513
|
-
<td align="center">
|
|
514
|
-
<table width="100%" cellpadding="0" cellspacing="0" style="max-width: 480px; background-color: #ffffff; border-radius: 16px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.06); border-left: 4px solid #c15f3c;">
|
|
515
|
-
<tr>
|
|
516
|
-
<td style="padding: 40px;">
|
|
517
|
-
<p style="margin: 0 0 20px; font-size: 12px; font-weight: 600; color: #c15f3c; text-transform: uppercase; letter-spacing: 1.5px;">Password Reset</p>
|
|
518
|
-
<h1 style="margin: 0 0 8px; font-size: 22px; font-weight: 600; color: #1a170f;">Choose a new password</h1>
|
|
519
|
-
<p style="margin: 0 0 28px; font-size: 15px; color: #6b6560; line-height: 1.6;">
|
|
520
|
-
Hi ${safeName}, we received a request to reset your password. Click the button below to continue.
|
|
521
|
-
</p>
|
|
522
|
-
<a href="${resetUrl}" style="display: inline-block; background-color: #1a170f; color: #ffffff; padding: 14px 32px; border-radius: 10px; text-decoration: none; font-size: 15px; font-weight: 600;">
|
|
523
|
-
Reset password →
|
|
524
|
-
</a>
|
|
525
|
-
<p style="margin: 28px 0 0; font-size: 13px; color: #9b958e; line-height: 1.6;">
|
|
526
|
-
This link expires in 1 hour. If you didn't request this, you can safely ignore this email.
|
|
527
|
-
</p>
|
|
528
|
-
</td>
|
|
529
|
-
</tr>
|
|
530
|
-
<tr>
|
|
531
|
-
<td style="padding: 0 40px 32px;">
|
|
532
|
-
<div style="border-top: 1px solid #e8e6e1; padding-top: 20px;">
|
|
533
|
-
<p style="margin: 0; font-size: 12px; color: #b5b0a8; line-height: 1.5;">
|
|
534
|
-
If the button doesn't work, copy this link:<br/>
|
|
535
|
-
<a href="${resetUrl}" style="color: #c15f3c; text-decoration: underline; word-break: break-all;">${resetUrl}</a>
|
|
536
|
-
</p>
|
|
537
|
-
</div>
|
|
538
|
-
</td>
|
|
539
|
-
</tr>
|
|
540
|
-
</table>
|
|
541
|
-
</td>
|
|
542
|
-
</tr>
|
|
543
|
-
</table>
|
|
544
|
-
`,
|
|
545
|
-
});
|
|
546
|
-
|
|
547
|
-
logger.info({ userId: user.id }, '[AUTH] Password reset email sent');
|
|
548
|
-
} catch (error) {
|
|
549
|
-
// Log but don't throw — prevents leaking email existence via 500 vs 200
|
|
550
|
-
logger.error({ userId: user.id, err: error }, '[AUTH] Failed to send password reset email');
|
|
551
|
-
}
|
|
362
|
+
await enqueueRecovery(email);
|
|
552
363
|
}
|
|
553
364
|
|
|
554
365
|
export async function resetPassword(token: string, newPassword: string): Promise<void> {
|
|
555
|
-
assertRedisReady('Password reset');
|
|
556
|
-
const
|
|
557
|
-
|
|
558
|
-
// GETDEL reads and removes the token in one step, so a link used twice at
|
|
559
|
-
// the same instant changes the password only once: the second request finds
|
|
560
|
-
// nothing. (A separate GET then DEL let both requests through.) Consumed
|
|
561
|
-
// before the work below, so a failure after this point means a new link.
|
|
562
|
-
const userId = await redis.getdel(`${PASSWORD_RESET_PREFIX}${hashToken(token)}`);
|
|
563
|
-
if (!userId) {
|
|
564
|
-
throw new BadRequestError('Invalid or expired reset token', 'INVALID_RESET_TOKEN');
|
|
565
|
-
}
|
|
366
|
+
assertRedisReady('Password reset');
|
|
367
|
+
const invalid = (): BadRequestError => new BadRequestError('Invalid or expired reset token', 'INVALID_RESET_TOKEN');
|
|
566
368
|
|
|
369
|
+
// Read the password before consumption. The SQL transaction checks this
|
|
370
|
+
// same version under lock before changing it and revoking its sessions.
|
|
371
|
+
const userId = await findRecoveryOwner(token);
|
|
372
|
+
if (!userId) throw invalid();
|
|
567
373
|
const user = await authRepo.findUserById(userId);
|
|
568
|
-
if (!user)
|
|
569
|
-
throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
570
|
-
}
|
|
374
|
+
if (!user || !await consumeRecoveryToken(userId, token)) throw invalid();
|
|
571
375
|
|
|
572
376
|
const hashedPassword = await hashPassword(newPassword);
|
|
573
|
-
await authRepo.
|
|
574
|
-
|
|
575
|
-
// The per-user pointer to the (now consumed) token
|
|
576
|
-
await redis.del(`${PASSWORD_RESET_USER_PREFIX}${userId}`);
|
|
577
|
-
|
|
578
|
-
// Invalidate all sessions for security (force re-login with new password)
|
|
579
|
-
await sessionRepository.deleteAllUserSessions(userId);
|
|
580
|
-
await authRepo.deleteRefreshTokensByUserId(userId);
|
|
581
|
-
|
|
377
|
+
if (!await authRepo.commitPasswordRecovery(userId, user.password, hashedPassword)) throw invalid();
|
|
582
378
|
logger.info({ userId }, '[AUTH] Password reset completed');
|
|
583
379
|
}
|