create-tigra 4.0.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/README.md +21 -3
- package/bin/create-tigra.js +131 -65
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +123 -0
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +145 -0
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +75 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +20 -0
- package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
- package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +123 -0
- package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
- package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
- package/modules/diagnostics/server/diagnostics.context.ts +73 -0
- package/modules/diagnostics/server/diagnostics.repo.ts +79 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +16 -0
- package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
- package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
- package/modules/diagnostics/server/diagnostics.service.ts +44 -0
- 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 +37 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -0
- package/modules/metrics/client/metrics.pages.ts +5 -0
- package/modules/metrics/performance.md +56 -0
- package/modules/metrics/prisma/metric-bucket.prisma +18 -0
- package/modules/metrics/prisma/migration.sql +17 -0
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +97 -0
- package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
- package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
- package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
- package/modules/metrics/server/metrics.collector.ts +133 -0
- package/modules/metrics/server/metrics.pages.ts +3 -0
- package/modules/metrics/server/metrics.repo.ts +45 -0
- package/modules/metrics/server/metrics.routes.ts +45 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +104 -0
- package/package.json +1 -1
- package/template/AGENTS.md +18 -10
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/src/app/focus-rings.policy.test.ts +88 -0
- package/template/client/src/app/globals.css +46 -0
- package/template/client/src/app/layout.tsx +5 -0
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
- package/template/client/src/components/ui/input.tsx +3 -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/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -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
|
@@ -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
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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
|
|
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
|
-
//
|
|
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
|
|
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({
|