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,4 +1,5 @@
|
|
|
1
|
-
import { afterAll, beforeAll, expect, it } from 'vitest';
|
|
1
|
+
import { afterAll, beforeAll, expect, it, vi } from 'vitest';
|
|
2
|
+
import { Prisma } from '@prisma/client';
|
|
2
3
|
import type { FastifyInstance } from 'fastify';
|
|
3
4
|
import { buildTestApp, db, registerAdmin, registerUser } from '@/test/integration-helpers.js';
|
|
4
5
|
|
|
@@ -20,7 +21,7 @@ it('allows only administrators to read stored diagnostics and validates bounded
|
|
|
20
21
|
const headers = { cookie: admin.jar.header() };
|
|
21
22
|
const read = await app.inject({ url, headers });
|
|
22
23
|
expect(read.statusCode).toBe(200);
|
|
23
|
-
expect(read.headers['cache-control']).toBe('no-store');
|
|
24
|
+
expect(read.headers['cache-control']).toBe('private, no-store');
|
|
24
25
|
expect(read.json().data).toEqual({ groups: [], nextCursor: null });
|
|
25
26
|
for (const query of [
|
|
26
27
|
`from=invalid&to=${to}`,
|
|
@@ -32,6 +33,21 @@ it('allows only administrators to read stored diagnostics and validates bounded
|
|
|
32
33
|
]) expect((await app.inject({ url: `${base}?${query}`, headers })).statusCode).toBe(422);
|
|
33
34
|
});
|
|
34
35
|
|
|
36
|
+
it('returns a safe retryable error when MySQL cancels an expensive diagnostic query', async () => {
|
|
37
|
+
const { prisma } = await import('@libs/prisma.js');
|
|
38
|
+
const admin = await registerAdmin(app, 'diagnostics-timeout');
|
|
39
|
+
const query = vi.spyOn(prisma, '$queryRaw').mockRejectedValueOnce(new Prisma.PrismaClientKnownRequestError('Fixture private detail', {
|
|
40
|
+
code: 'P2010', clientVersion: 'fixture', meta: { code: '3024' },
|
|
41
|
+
}));
|
|
42
|
+
try {
|
|
43
|
+
const read = await app.inject({ url, headers: { cookie: admin.jar.header() } });
|
|
44
|
+
expect(query.mock.calls[0]?.[0].toString()).toContain('MAX_EXECUTION_TIME(1500)');
|
|
45
|
+
expect(read.statusCode).toBe(503);
|
|
46
|
+
expect(read.json().error.code).toBe('DIAGNOSTICS_QUERY_TIMEOUT');
|
|
47
|
+
expect(read.body).not.toContain('Fixture private detail');
|
|
48
|
+
} finally { query.mockRestore(); }
|
|
49
|
+
});
|
|
50
|
+
|
|
35
51
|
it('stores typed failures and jobs once and ignores expected errors and raw messages', async () => {
|
|
36
52
|
const { buildApp } = await import('@/app.js');
|
|
37
53
|
const { startRecurringJob } = await import('@/jobs/schedule.js');
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Prisma } from '@prisma/client';
|
|
2
2
|
import { prisma } from '@libs/prisma.js';
|
|
3
|
+
import { ServiceUnavailableError } from '@shared/errors/errors.js';
|
|
3
4
|
import type { DiagnosticBucket } from './diagnostics.collector.js';
|
|
4
5
|
import type { DiagnosticFrame, DiagnosticSeverity, DiagnosticSource } from './diagnostics.sample.js';
|
|
5
6
|
import type { DiagnosticsQuery } from './diagnostics.schemas.js';
|
|
@@ -35,6 +36,8 @@ export async function readDiagnosticGroups(query: DiagnosticsQuery): Promise<{
|
|
|
35
36
|
groups: DiagnosticGroup[]; nextCursor: string | null;
|
|
36
37
|
}> {
|
|
37
38
|
const { from, to, severity, groupId, limit, cursor } = query;
|
|
39
|
+
// LIMIT bounds the response. The optimizer hint bounds the aggregation
|
|
40
|
+
// that MySQL has to complete before it can return that response.
|
|
38
41
|
const rows = await prisma.$queryRaw<RankedRow[]>`
|
|
39
42
|
WITH summaries AS (
|
|
40
43
|
SELECT group_id, CAST(SUM(occurrences) AS UNSIGNED) AS occurrence_count,
|
|
@@ -49,7 +52,8 @@ export async function readDiagnosticGroups(query: DiagnosticsQuery): Promise<{
|
|
|
49
52
|
SELECT summaries.*, ROW_NUMBER() OVER (ORDER BY occurrence_count DESC, group_id ASC) AS group_rank
|
|
50
53
|
FROM summaries
|
|
51
54
|
)
|
|
52
|
-
SELECT
|
|
55
|
+
SELECT /*+ MAX_EXECUTION_TIME(1500) */ ranked.group_rank AS groupRank,
|
|
56
|
+
ranked.group_id AS groupId, ranked.occurrence_count AS occurrenceCount,
|
|
53
57
|
ranked.first_seen AS firstSeen, ranked.last_seen AS lastSeen,
|
|
54
58
|
sample.severity, sample.source, sample.label, sample.code, sample.message, sample.frames, sample.release
|
|
55
59
|
FROM ranked
|
|
@@ -57,7 +61,13 @@ export async function readDiagnosticGroups(query: DiagnosticsQuery): Promise<{
|
|
|
57
61
|
${cursor ? Prisma.sql`WHERE ranked.occurrence_count < ${cursor[0]}
|
|
58
62
|
OR (ranked.occurrence_count = ${cursor[0]} AND ranked.group_id > ${cursor[1]})` : Prisma.empty}
|
|
59
63
|
ORDER BY ranked.group_rank ASC
|
|
60
|
-
LIMIT ${limit + 1}
|
|
64
|
+
LIMIT ${limit + 1}`.catch((error: unknown) => {
|
|
65
|
+
// Prisma wraps MySQL's statement-timeout code in raw-query metadata.
|
|
66
|
+
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2010' && String(error.meta?.code) === '3024') {
|
|
67
|
+
throw new ServiceUnavailableError('Diagnostics query timed out. Try a narrower interval.', 'DIAGNOSTICS_QUERY_TIMEOUT');
|
|
68
|
+
}
|
|
69
|
+
throw error;
|
|
70
|
+
});
|
|
61
71
|
const groups = rows.slice(0, limit).map(({ groupRank, occurrenceCount, ...row }) => ({
|
|
62
72
|
...row, rank: Number(groupRank), count: Number(occurrenceCount),
|
|
63
73
|
}));
|
|
@@ -10,8 +10,7 @@ export function registerAdminDiagnosticsRoute(app: FastifyInstance): void {
|
|
|
10
10
|
app.get<{ Querystring: DiagnosticsQuery }>(DIAGNOSTICS_PATH, {
|
|
11
11
|
schema: { querystring: diagnosticsQuerySchema },
|
|
12
12
|
config: { rateLimit: RATE_LIMITS.ADMIN_DEFAULT },
|
|
13
|
-
}, async (request
|
|
14
|
-
reply.header('Cache-Control', 'no-store');
|
|
13
|
+
}, async (request) => {
|
|
15
14
|
return successResponse('Diagnostic groups', await readDiagnosticGroups(request.query));
|
|
16
15
|
});
|
|
17
16
|
}
|
|
@@ -3,12 +3,11 @@
|
|
|
3
3
|
import { useMutation } from '@tanstack/react-query';
|
|
4
4
|
import { toast } from 'sonner';
|
|
5
5
|
|
|
6
|
-
import { useAppDispatch } from '@/store/hooks';
|
|
7
6
|
import { useAppRouter } from '@/hooks/useAppRouter';
|
|
8
7
|
import { getErrorMessage, isErrorCode, isLimitError, ERROR_CODES } from '@/lib/utils/error';
|
|
9
8
|
import { ROUTES } from '@/lib/constants/routes';
|
|
10
9
|
import { verificationService } from '../services/verification.service';
|
|
11
|
-
import {
|
|
10
|
+
import { useSessionTransition } from './useSessionTransition';
|
|
12
11
|
|
|
13
12
|
interface UseSendVerificationReturn {
|
|
14
13
|
sendVerification: (email: string) => void;
|
|
@@ -47,15 +46,13 @@ interface UseVerifyAccountReturn {
|
|
|
47
46
|
}
|
|
48
47
|
|
|
49
48
|
export const useVerifyAccount = (): UseVerifyAccountReturn => {
|
|
50
|
-
const dispatch = useAppDispatch();
|
|
51
49
|
const router = useAppRouter();
|
|
50
|
+
const { completeSessionChange } = useSessionTransition();
|
|
52
51
|
|
|
53
52
|
const mutation = useMutation({
|
|
54
53
|
mutationFn: (token: string) => verificationService.verifyAccount(token),
|
|
55
|
-
onSuccess: (
|
|
56
|
-
|
|
57
|
-
toast.success('Account verified successfully!');
|
|
58
|
-
router.push(ROUTES.DASHBOARD);
|
|
54
|
+
onSuccess: () => {
|
|
55
|
+
completeSessionChange(ROUTES.DASHBOARD);
|
|
59
56
|
},
|
|
60
57
|
onError: (error: unknown) => {
|
|
61
58
|
if (isLimitError(error)) return; // the global toast already says how long to wait
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
19
19
|
import type { FastifyInstance } from 'fastify';
|
|
20
|
+
import { randomUUID } from 'node:crypto';
|
|
20
21
|
import {
|
|
21
22
|
PASSWORD,
|
|
22
23
|
buildTestApp,
|
|
@@ -92,6 +93,22 @@ describe('the verification link', () => {
|
|
|
92
93
|
if ((await r.type(key)) === 'string') expect((await r.get(key)) ?? '').not.toContain(token);
|
|
93
94
|
}
|
|
94
95
|
});
|
|
96
|
+
|
|
97
|
+
it('keeps the latest issuance when an older delivery is retried', async () => {
|
|
98
|
+
// Load Redis-dependent modules after the mail stub and test env are set.
|
|
99
|
+
const { authLinkStore } = await import('../auth-link-store.js');
|
|
100
|
+
const links = authLinkStore('verify:', 'verify-user:', 'verify-order:');
|
|
101
|
+
const account = randomUUID();
|
|
102
|
+
const old = randomUUID();
|
|
103
|
+
const current = randomUUID();
|
|
104
|
+
expect(await links.issue(account, old, '101-0')).toBe(true);
|
|
105
|
+
expect(await links.issue(account, current, '101-1')).toBe(true);
|
|
106
|
+
expect(await links.issue(account, old, '101-0')).toBe(false);
|
|
107
|
+
expect(await links.findOwner(old)).toBeNull();
|
|
108
|
+
expect(await links.findOwner(current)).toBe(account);
|
|
109
|
+
expect(await links.consume(account, current)).toBe(true);
|
|
110
|
+
expect(await links.issue(account, current, '101-1')).toBe(false);
|
|
111
|
+
});
|
|
95
112
|
});
|
|
96
113
|
|
|
97
114
|
describe('send-verification', () => {
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { beforeEach, expect, it, vi } from 'vitest';
|
|
2
|
+
import { testUsers } from '@/test/setup.js';
|
|
3
|
+
import { sendVerification, verifyAccount } from '../verification.service.js';
|
|
4
|
+
|
|
5
|
+
const fixture = vi.hoisted(() => ({
|
|
6
|
+
redis: { eval: vi.fn(), get: vi.fn(), status: 'ready' },
|
|
7
|
+
db: { user: { update: vi.fn() }, session: { create: vi.fn() } },
|
|
8
|
+
transaction: vi.fn(),
|
|
9
|
+
findEmail: vi.fn(),
|
|
10
|
+
lockUser: vi.fn(),
|
|
11
|
+
createRefreshToken: vi.fn(),
|
|
12
|
+
sendEmail: vi.fn(),
|
|
13
|
+
}));
|
|
14
|
+
vi.mock('@libs/redis.js', () => ({ getRedis: (): typeof fixture.redis => fixture.redis }));
|
|
15
|
+
vi.mock('@libs/redis-required.js');
|
|
16
|
+
vi.mock('@libs/prisma.js', () => ({ prisma: { $transaction: fixture.transaction }, isPrismaWriteConflict: (): boolean => false }));
|
|
17
|
+
vi.mock('../auth.repo.js', () => ({
|
|
18
|
+
findUserByEmail: fixture.findEmail,
|
|
19
|
+
lockUser: fixture.lockUser,
|
|
20
|
+
createRefreshToken: fixture.createRefreshToken,
|
|
21
|
+
}));
|
|
22
|
+
vi.mock('../session.repo.js', () => ({ sessionRepository: { createSession: fixture.db.session.create } }));
|
|
23
|
+
vi.mock('@libs/auth.js', () => ({
|
|
24
|
+
signAccessToken: (): string => 'fixture-access',
|
|
25
|
+
generateRefreshToken: (): string => 'fixture-refresh',
|
|
26
|
+
getRefreshTokenExpiresAt: (): Date => new Date(),
|
|
27
|
+
}));
|
|
28
|
+
vi.mock('@libs/email.js', () => ({ sendEmail: fixture.sendEmail }));
|
|
29
|
+
vi.mock('../auth.service.js', () => ({ sanitizeUser: (user: unknown): unknown => user }));
|
|
30
|
+
|
|
31
|
+
const user = { ...testUsers.validUser, emailVerifiedAt: null };
|
|
32
|
+
beforeEach(() => {
|
|
33
|
+
vi.resetAllMocks();
|
|
34
|
+
fixture.findEmail.mockResolvedValue(user);
|
|
35
|
+
fixture.lockUser.mockResolvedValue(user);
|
|
36
|
+
fixture.redis.get.mockResolvedValue(user.id);
|
|
37
|
+
fixture.db.session.create.mockResolvedValue({ id: 'fixture-session' });
|
|
38
|
+
fixture.db.user.update.mockResolvedValue({ ...user, emailVerifiedAt: new Date() });
|
|
39
|
+
fixture.transaction.mockImplementation(async write => write(fixture.db));
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('accepts a public resend without an account lookup or mail request', async () => {
|
|
43
|
+
fixture.redis.eval.mockResolvedValue(0);
|
|
44
|
+
await sendVerification(user.email);
|
|
45
|
+
expect(fixture.findEmail).not.toHaveBeenCalled();
|
|
46
|
+
expect(fixture.sendEmail).not.toHaveBeenCalled();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('returns a safe resend error if the database write fails after link consumption', async () => {
|
|
50
|
+
fixture.redis.eval.mockResolvedValue(1);
|
|
51
|
+
const failure = new Error('private fixture');
|
|
52
|
+
fixture.createRefreshToken.mockRejectedValueOnce(failure);
|
|
53
|
+
const redeem = verifyAccount('current-fixture-link');
|
|
54
|
+
await expect(redeem).rejects.toMatchObject({ statusCode: 503, code: 'VERIFICATION_RETRY' });
|
|
55
|
+
expect(fixture.sendEmail).not.toHaveBeenCalled();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('leaves account and session state untouched for a link that is no longer current', async () => {
|
|
59
|
+
fixture.redis.eval.mockResolvedValue(0);
|
|
60
|
+
await expect(verifyAccount('previous-fixture-link')).rejects.toMatchObject({
|
|
61
|
+
statusCode: 400, code: 'INVALID_VERIFICATION_TOKEN',
|
|
62
|
+
});
|
|
63
|
+
expect(fixture.db.user.update).not.toHaveBeenCalled();
|
|
64
|
+
expect(fixture.db.session.create).not.toHaveBeenCalled();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('requires Redis admission when the verification queue is full', async () => {
|
|
68
|
+
fixture.redis.eval.mockResolvedValue(-1);
|
|
69
|
+
await expect(sendVerification(user.email)).rejects.toMatchObject({ statusCode: 503 });
|
|
70
|
+
expect(fixture.findEmail).not.toHaveBeenCalled();
|
|
71
|
+
});
|
|
@@ -1,96 +1,56 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
import type { FastifyInstance } from 'fastify';
|
|
3
|
+
import type { User } from '@prisma/client';
|
|
2
4
|
import { signAccessToken, generateRefreshToken, getRefreshTokenExpiresAt } from '@libs/auth.js';
|
|
3
|
-
import { getRedis } from '@libs/redis.js';
|
|
4
5
|
import { sendEmail } from '@libs/email.js';
|
|
5
6
|
import { logger } from '@libs/logger.js';
|
|
6
7
|
import { env } from '@config/env.js';
|
|
7
8
|
import { ACCOUNT_DEACTIVATED } from '@libs/account-status.js';
|
|
8
|
-
import {
|
|
9
|
+
import { runAccountMutation } from '@libs/account-mutation.js';
|
|
10
|
+
import type { EmailQuotaBucket } from '@libs/email-quota.js';
|
|
9
11
|
import { assertRedisReady } from '@libs/redis-required.js';
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
ForbiddenError,
|
|
14
|
-
NotFoundError,
|
|
15
|
-
} from '@shared/errors/errors.js';
|
|
12
|
+
import { BadRequestError, ForbiddenError, NotFoundError, ServiceUnavailableError } from '@shared/errors/errors.js';
|
|
13
|
+
import { enqueueAuthMail, startAuthMailWorker } from './auth-mail-queue.js';
|
|
14
|
+
import { authLinkStore } from './auth-link-store.js';
|
|
16
15
|
import * as authRepo from './auth.repo.js';
|
|
17
16
|
import { sessionRepository } from './session.repo.js';
|
|
18
|
-
import { sanitizeUser } from './auth.service.js';
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const VERIFICATION_PREFIX = 'verify:';
|
|
26
|
-
const VERIFICATION_USER_PREFIX = 'verify-user:';
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* Send a verification email to a user.
|
|
30
|
-
* Public endpoint — accepts email, silent return if user not found (prevents enumeration).
|
|
31
|
-
* Also called internally by the register and login flows for auto-sending.
|
|
32
|
-
*
|
|
33
|
-
* Verification proves email ownership and nothing else: it sets
|
|
34
|
-
* `emailVerifiedAt` and never touches `isActive` (the admin ban switch).
|
|
35
|
-
*/
|
|
36
|
-
export async function sendVerification(
|
|
17
|
+
import { sanitizeUser, type AuthResult } from './auth.service.js';
|
|
18
|
+
|
|
19
|
+
const stream = 'email-verification:jobs';
|
|
20
|
+
const verificationLinks = authLinkStore('verify:', 'verify-user:', 'verify-order:');
|
|
21
|
+
|
|
22
|
+
/** Public callers only wait for admission, regardless of whether mail will be sent. */
|
|
23
|
+
export function sendVerification(
|
|
37
24
|
email: string,
|
|
38
25
|
{ quota = 'public' }: { quota?: EmailQuotaBucket | 'none' } = {},
|
|
39
26
|
): Promise<void> {
|
|
40
|
-
//
|
|
41
|
-
//
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
// Over the cap it answers 429 EMAIL_RATE_LIMITED with the wait.
|
|
45
|
-
// - 'sign-in': the resend after a correct password; its own counter, so
|
|
46
|
-
// strangers typing the address cannot use it up.
|
|
47
|
-
// - 'none': the one email sent at register (an address registers only once).
|
|
48
|
-
// Register and the sign-in resend call this fire-and-forget: over their cap
|
|
49
|
-
// the email is skipped and the caller logs it.
|
|
50
|
-
//
|
|
51
|
-
// Verification tokens live in Redis: without it, answer a clear 503 for every
|
|
52
|
-
// address (checked first, so it reveals nothing about the account).
|
|
53
|
-
assertRedisReady('Email verification');
|
|
54
|
-
if (quota !== 'none') {
|
|
55
|
-
await consumeEmailQuota(email, quota);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const user = await authRepo.findUserByEmail(email);
|
|
59
|
-
|
|
60
|
-
// Silent return if user not found — prevents email enumeration (same pattern as forgotPassword)
|
|
61
|
-
if (!user) return;
|
|
62
|
-
|
|
63
|
-
// No token for a banned account: a verify link must never lift an admin ban
|
|
64
|
-
// (that is exactly how a banned user used to re-activate themselves). No
|
|
65
|
-
// token either when the email is already verified. Both stay silent so the
|
|
66
|
-
// response does not reveal the account's status.
|
|
67
|
-
if (!user.isActive || user.emailVerifiedAt) return;
|
|
68
|
-
|
|
69
|
-
const redis = getRedis();
|
|
70
|
-
|
|
71
|
-
// Invalidate any existing verification token for this user (the pointer holds its fingerprint)
|
|
72
|
-
const existingTokenHash = await redis.get(`${VERIFICATION_USER_PREFIX}${user.id}`);
|
|
73
|
-
if (existingTokenHash) {
|
|
74
|
-
await redis.del(`${VERIFICATION_PREFIX}${existingTokenHash}`);
|
|
75
|
-
await redis.del(`${VERIFICATION_USER_PREFIX}${user.id}`);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// Generate a secure token; only its fingerprint goes to Redis (1 hour TTL)
|
|
79
|
-
const token = crypto.randomBytes(32).toString('hex');
|
|
80
|
-
const tokenHash = hashToken(token);
|
|
81
|
-
|
|
82
|
-
await redis.set(`${VERIFICATION_PREFIX}${tokenHash}`, user.id, 'EX', VERIFICATION_TTL);
|
|
83
|
-
await redis.set(`${VERIFICATION_USER_PREFIX}${user.id}`, tokenHash, 'EX', VERIFICATION_TTL);
|
|
27
|
+
// Public resends share their address quota with recovery. Reserve the last
|
|
28
|
+
// 200 slots for first registration and callers who have proved a password.
|
|
29
|
+
return enqueueAuthMail(stream, email, quota, quota === 'public' ? 800 : 1_000, 'Email verification');
|
|
30
|
+
}
|
|
84
31
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
32
|
+
export function startEmailVerificationJob(app: FastifyInstance): void {
|
|
33
|
+
startAuthMailWorker(app, stream, 'email-verification', deliverVerification);
|
|
34
|
+
}
|
|
88
35
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
36
|
+
async function deliverVerification(id: string, email: string): Promise<void> {
|
|
37
|
+
const user = await authRepo.findUserByEmail(email);
|
|
38
|
+
if (!user?.isActive || user.emailVerifiedAt) return;
|
|
39
|
+
|
|
40
|
+
// A retry must reuse the same link, body and provider key. Avoid embedding
|
|
41
|
+
// editable profile fields in the mail body because they can change mid-retry.
|
|
42
|
+
const token = createHmac('sha256', env.JWT_SECRET)
|
|
43
|
+
.update('tigra/email-verification/v1/' + id + '/' + user.id).digest('hex');
|
|
44
|
+
if (!await verificationLinks.issue(user.id, token, id)) return;
|
|
45
|
+
const deliveryKey = createHmac('sha256', env.JWT_SECRET)
|
|
46
|
+
.update('tigra/email-verification-delivery/v1/' + env.CLIENT_URL + '/' + id).digest('hex');
|
|
47
|
+
const verifyUrl = env.CLIENT_URL + '/verify-account?token=' + token;
|
|
48
|
+
|
|
49
|
+
await sendEmail({
|
|
50
|
+
to: user.email,
|
|
51
|
+
subject: 'Verify your account',
|
|
52
|
+
idempotencyKey: 'email-verification/' + deliveryKey,
|
|
53
|
+
html: `
|
|
94
54
|
<table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f3ee; padding: 40px 20px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
|
|
95
55
|
<tr>
|
|
96
56
|
<td align="center">
|
|
@@ -100,7 +60,7 @@ export async function sendVerification(
|
|
|
100
60
|
<p style="margin: 0 0 20px; font-size: 12px; font-weight: 600; color: #c15f3c; text-transform: uppercase; letter-spacing: 1.5px;">Account Verification</p>
|
|
101
61
|
<h1 style="margin: 0 0 8px; font-size: 22px; font-weight: 600; color: #1a170f;">Verify your account</h1>
|
|
102
62
|
<p style="margin: 0 0 28px; font-size: 15px; color: #6b6560; line-height: 1.6;">
|
|
103
|
-
|
|
63
|
+
Hello, please verify your email address to activate your account and get started.
|
|
104
64
|
</p>
|
|
105
65
|
<a href="${verifyUrl}" style="display: inline-block; background-color: #1a170f; color: #ffffff; padding: 14px 32px; border-radius: 10px; text-decoration: none; font-size: 15px; font-weight: 600;">
|
|
106
66
|
Verify account →
|
|
@@ -124,14 +84,21 @@ export async function sendVerification(
|
|
|
124
84
|
</td>
|
|
125
85
|
</tr>
|
|
126
86
|
</table>
|
|
127
|
-
|
|
128
|
-
|
|
87
|
+
`,
|
|
88
|
+
});
|
|
89
|
+
logger.info({ userId: user.id }, '[AUTH] Verification email sent');
|
|
90
|
+
}
|
|
129
91
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
92
|
+
type VerificationResult =
|
|
93
|
+
| { kind: 'invalid' | 'deleted' | 'inactive' | 'verified' }
|
|
94
|
+
| { kind: 'success'; user: User; sessionId: string };
|
|
95
|
+
|
|
96
|
+
function verifyUnavailable(): ServiceUnavailableError {
|
|
97
|
+
return new ServiceUnavailableError('Email verification is temporarily unavailable. Please try again.');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function newLinkRequired(): ServiceUnavailableError {
|
|
101
|
+
return new ServiceUnavailableError('Verification did not complete. Please request a new verification link.', 'VERIFICATION_RETRY');
|
|
135
102
|
}
|
|
136
103
|
|
|
137
104
|
export async function verifyAccount(
|
|
@@ -139,74 +106,56 @@ export async function verifyAccount(
|
|
|
139
106
|
deviceInfo?: string,
|
|
140
107
|
ipAddress?: string,
|
|
141
108
|
): Promise<AuthResult> {
|
|
142
|
-
assertRedisReady('Email verification');
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
// ioredis exposes GETDEL as getdel (all lowercase); getDel does not exist.
|
|
147
|
-
const userId = await redis.getdel(`${VERIFICATION_PREFIX}${hashToken(token)}`);
|
|
148
|
-
if (!userId) {
|
|
149
|
-
throw new BadRequestError('Invalid or expired verification token', 'INVALID_VERIFICATION_TOKEN');
|
|
150
|
-
}
|
|
109
|
+
assertRedisReady('Email verification');
|
|
110
|
+
const invalid = (): BadRequestError => new BadRequestError('Invalid or expired verification token', 'INVALID_VERIFICATION_TOKEN');
|
|
111
|
+
const userId = await verificationLinks.findOwner(token).catch(() => { throw verifyUnavailable(); });
|
|
112
|
+
if (!userId) throw invalid();
|
|
151
113
|
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
114
|
+
const refreshToken = generateRefreshToken();
|
|
115
|
+
const expiresAt = getRefreshTokenExpiresAt();
|
|
116
|
+
let consumed = false;
|
|
117
|
+
let result: VerificationResult;
|
|
118
|
+
try {
|
|
119
|
+
result = await runAccountMutation<VerificationResult>(async tx => {
|
|
120
|
+
// The account row orders verification against ban, deletion and sign-in.
|
|
121
|
+
// A transaction retry may proceed only before the irreversible Redis step.
|
|
122
|
+
if (consumed) throw newLinkRequired();
|
|
123
|
+
const account = await authRepo.lockUser(tx, userId);
|
|
124
|
+
consumed = await verificationLinks.consume(userId, token).catch(() => { throw newLinkRequired(); });
|
|
125
|
+
if (!consumed) return { kind: 'invalid' };
|
|
126
|
+
if (!account || account.deletedAt) return { kind: 'deleted' };
|
|
127
|
+
if (!account.isActive) return { kind: 'inactive' };
|
|
128
|
+
if (account.emailVerifiedAt) return { kind: 'verified' };
|
|
129
|
+
|
|
130
|
+
const user = await tx.user.update({ where: { id: userId }, data: { emailVerifiedAt: new Date() } });
|
|
131
|
+
const session = await sessionRepository.createSession({ userId, deviceInfo, ipAddress, expiresAt }, tx);
|
|
132
|
+
await authRepo.createRefreshToken({ token: refreshToken, userId, sessionId: session.id, expiresAt }, tx);
|
|
133
|
+
return { kind: 'success', user, sessionId: session.id };
|
|
134
|
+
});
|
|
135
|
+
} catch (error) {
|
|
136
|
+
// MySQL can roll back even after Redis consumed the link. Never reinstate
|
|
137
|
+
// the old link, since a newer one might already have been issued.
|
|
138
|
+
if (consumed) {
|
|
139
|
+
logger.warn({ userId }, '[AUTH] Verification transaction did not complete');
|
|
140
|
+
throw newLinkRequired();
|
|
141
|
+
}
|
|
142
|
+
throw error;
|
|
155
143
|
}
|
|
156
144
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
throw new ForbiddenError(
|
|
163
|
-
'This account has been deactivated. Contact support if you think this is a mistake.',
|
|
164
|
-
ACCOUNT_DEACTIVATED,
|
|
145
|
+
switch (result.kind) {
|
|
146
|
+
case 'invalid': throw invalid();
|
|
147
|
+
case 'deleted': throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
148
|
+
case 'inactive': throw new ForbiddenError(
|
|
149
|
+
'This account has been deactivated. Contact support if you think this is a mistake.', ACCOUNT_DEACTIVATED,
|
|
165
150
|
);
|
|
151
|
+
case 'verified': throw new BadRequestError('This email address is already verified', 'ALREADY_VERIFIED');
|
|
152
|
+
case 'success': break;
|
|
166
153
|
}
|
|
167
154
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const verifiedAt = new Date();
|
|
171
|
-
const marked = await authRepo.markEmailVerified(userId, verifiedAt);
|
|
172
|
-
if (!marked) {
|
|
173
|
-
const current = await authRepo.findUserById(userId);
|
|
174
|
-
if (!current || !current.isActive) {
|
|
175
|
-
throw new ForbiddenError(
|
|
176
|
-
'This account has been deactivated. Contact support if you think this is a mistake.',
|
|
177
|
-
ACCOUNT_DEACTIVATED,
|
|
178
|
-
);
|
|
179
|
-
}
|
|
180
|
-
throw new BadRequestError('This email address is already verified', 'ALREADY_VERIFIED');
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// Generate tokens and create session (same pattern as login)
|
|
184
|
-
// Session first: the access token carries its id (see authenticate()).
|
|
185
|
-
const refreshToken = generateRefreshToken();
|
|
186
|
-
const refreshTokenExpiresAt = getRefreshTokenExpiresAt();
|
|
187
|
-
|
|
188
|
-
const session = await sessionRepository.createSession({
|
|
189
|
-
userId: user.id,
|
|
190
|
-
deviceInfo,
|
|
191
|
-
ipAddress,
|
|
192
|
-
expiresAt: refreshTokenExpiresAt,
|
|
193
|
-
});
|
|
194
|
-
|
|
195
|
-
const accessToken = signAccessToken({
|
|
196
|
-
userId: user.id,
|
|
197
|
-
role: user.role,
|
|
198
|
-
sessionId: session.id,
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
await authRepo.createRefreshToken({
|
|
202
|
-
token: refreshToken,
|
|
203
|
-
userId: user.id,
|
|
204
|
-
sessionId: session.id,
|
|
205
|
-
expiresAt: refreshTokenExpiresAt,
|
|
206
|
-
});
|
|
207
|
-
|
|
155
|
+
const { user, sessionId } = result;
|
|
156
|
+
const accessToken = signAccessToken({ userId, role: user.role, sessionId });
|
|
208
157
|
logger.info({ userId }, '[AUTH] Account verified');
|
|
209
|
-
|
|
158
|
+
|
|
210
159
|
// Send welcome email (best-effort — don't fail verification if email fails)
|
|
211
160
|
const safeName = user.firstName.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
212
161
|
const dashboardUrl = `${env.CLIENT_URL}/dashboard`;
|
|
@@ -238,13 +187,9 @@ export async function verifyAccount(
|
|
|
238
187
|
</table>
|
|
239
188
|
`,
|
|
240
189
|
});
|
|
241
|
-
} catch
|
|
242
|
-
logger.error({ userId
|
|
190
|
+
} catch {
|
|
191
|
+
logger.error({ userId }, '[AUTH] Failed to send welcome email');
|
|
243
192
|
}
|
|
244
193
|
|
|
245
|
-
return {
|
|
246
|
-
|
|
247
|
-
accessToken,
|
|
248
|
-
refreshToken,
|
|
249
|
-
};
|
|
250
|
-
}
|
|
194
|
+
return { user: sanitizeUser(user), accessToken, refreshToken };
|
|
195
|
+
}
|
|
@@ -26,6 +26,8 @@ export function WebVitalsReporter(): null {
|
|
|
26
26
|
method: 'POST',
|
|
27
27
|
headers: { 'Content-Type': 'application/json' },
|
|
28
28
|
credentials: 'omit',
|
|
29
|
+
// Same-origin submissions can otherwise send the page, including its query.
|
|
30
|
+
referrerPolicy: 'no-referrer',
|
|
29
31
|
keepalive: true,
|
|
30
32
|
body: JSON.stringify({ page: visit.page, samples: [{ kind: name.toLowerCase(), value }] }),
|
|
31
33
|
}).catch(() => {});
|
|
@@ -46,6 +46,7 @@ it('sends one anonymous measurement per vital and retains its document page grou
|
|
|
46
46
|
method: 'POST',
|
|
47
47
|
headers: { 'Content-Type': 'application/json' },
|
|
48
48
|
credentials: 'omit',
|
|
49
|
+
referrerPolicy: 'no-referrer',
|
|
49
50
|
keepalive: true,
|
|
50
51
|
body: '{"page":"home","samples":[{"kind":"lcp","value":160}]}',
|
|
51
52
|
});
|
|
@@ -49,8 +49,8 @@ server metrics page allowlist together. Match dynamic routes to a fixed group.
|
|
|
49
49
|
Web Vitals describe a document visit, so client navigation does not relabel
|
|
50
50
|
earlier observations. Browser delivery is best-effort. Each vital is sent at
|
|
51
51
|
most once per document, including when Back restores that document from
|
|
52
|
-
cache. Sends are not automatically retried.
|
|
53
|
-
mean per sample period.
|
|
52
|
+
cache. Sends omit credentials and referrers and are not automatically retried.
|
|
53
|
+
Node event-loop delay records one mean per sample period.
|
|
54
54
|
|
|
55
55
|
Verify new measurements in a running generated app and check stored buckets
|
|
56
56
|
through the admin API. Keep user data and secrets out of metric labels.
|
|
@@ -73,3 +73,25 @@ test('bounds labels and pending windows during storage failure', async () => {
|
|
|
73
73
|
assert.deepEqual(written.map((row) => row.label), ['first', 'second', 'first']);
|
|
74
74
|
assert.ok(collector.droppedSamples >= 4);
|
|
75
75
|
});
|
|
76
|
+
|
|
77
|
+
test('stops draining future writes after the shutdown signal aborts', async () => {
|
|
78
|
+
let now = start;
|
|
79
|
+
let finish!: () => void;
|
|
80
|
+
const firstWrite = new Promise<void>((resolve) => { finish = resolve; });
|
|
81
|
+
const calls: MetricBucket[][] = [];
|
|
82
|
+
const collector = new MetricCollector(async (rows) => {
|
|
83
|
+
calls.push(rows);
|
|
84
|
+
if (calls.length === 1) await firstWrite;
|
|
85
|
+
}, { clock: (): number => now, release: null });
|
|
86
|
+
collector.record('operation', 'first', 10);
|
|
87
|
+
now += windowMs;
|
|
88
|
+
void collector.flush();
|
|
89
|
+
collector.record('operation', 'second', 10);
|
|
90
|
+
const controller = new AbortController();
|
|
91
|
+
const closing = collector.close(controller.signal);
|
|
92
|
+
await Promise.resolve();
|
|
93
|
+
controller.abort();
|
|
94
|
+
finish();
|
|
95
|
+
await closing;
|
|
96
|
+
assert.equal(calls.length, 1);
|
|
97
|
+
});
|
|
@@ -120,10 +120,13 @@ export class MetricCollector {
|
|
|
120
120
|
return this.writing;
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
-
/**
|
|
124
|
-
async close(): Promise<void> {
|
|
123
|
+
/** Publish a partial final window only while the shutdown budget allows it. */
|
|
124
|
+
async close(signal?: AbortSignal): Promise<void> {
|
|
125
125
|
this.closed = true;
|
|
126
|
-
while (this.pending.length) await this.flush();
|
|
126
|
+
while (this.pending.length && !signal?.aborted) await this.flush();
|
|
127
|
+
// An already-running transaction has its own timeout. On return from it,
|
|
128
|
+
// the close hook must avoid starting any additional database work.
|
|
129
|
+
if (signal?.aborted) return;
|
|
127
130
|
this.seal();
|
|
128
131
|
await this.flush();
|
|
129
132
|
}
|
|
@@ -39,8 +39,7 @@ export function registerAdminMetricsRoute(app: FastifyInstance): void {
|
|
|
39
39
|
app.get<{ Querystring: MetricsQuery }>('/admin/metrics', {
|
|
40
40
|
schema: { querystring: metricsQuerySchema },
|
|
41
41
|
config: { rateLimit: RATE_LIMITS.ADMIN_DEFAULT },
|
|
42
|
-
}, async (request
|
|
43
|
-
reply.header('Cache-Control', 'no-store');
|
|
42
|
+
}, async (request) => {
|
|
44
43
|
return successResponse('Metric buckets', await readMetricBuckets(request.query));
|
|
45
44
|
});
|
|
46
45
|
}
|
|
@@ -79,12 +79,16 @@ export function registerMetrics(app: FastifyInstance): MetricCollector | undefin
|
|
|
79
79
|
if (activeCollector === collector) activeCollector = undefined;
|
|
80
80
|
// The collector shares the app's shutdown budget with Redis and Prisma.
|
|
81
81
|
// A stalled store must never keep the Fastify close hook waiting forever.
|
|
82
|
+
const stop = new AbortController();
|
|
82
83
|
let deadline: ReturnType<typeof setTimeout> | undefined;
|
|
83
84
|
try {
|
|
84
85
|
await Promise.race([
|
|
85
|
-
collector.close(),
|
|
86
|
+
collector.close(stop.signal),
|
|
86
87
|
new Promise<never>((_resolve, reject) => {
|
|
87
|
-
deadline = setTimeout(() =>
|
|
88
|
+
deadline = setTimeout(() => {
|
|
89
|
+
stop.abort();
|
|
90
|
+
reject(new Error('Metrics flush deadline'));
|
|
91
|
+
}, 2_500);
|
|
88
92
|
}),
|
|
89
93
|
]);
|
|
90
94
|
} catch {
|