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,92 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
/** Add static, application-owned summaries here. Never interpolate inputs. */
|
|
6
|
+
export const diagnosticMessages = {
|
|
7
|
+
DEPENDENCY_TIMEOUT: 'A dependency operation timed out',
|
|
8
|
+
DEPENDENCY_UNAVAILABLE: 'A dependency connection failed',
|
|
9
|
+
DEPENDENCY_HTTP_FAILURE: 'A dependency returned an unsuccessful HTTP response',
|
|
10
|
+
DEPENDENCY_RESPONSE_LIMIT: 'A dependency response exceeded its configured size limit',
|
|
11
|
+
DEPENDENCY_TARGET_REJECTED: 'The configured dependency target was rejected',
|
|
12
|
+
DATABASE_UNAVAILABLE: 'The database connection was unavailable',
|
|
13
|
+
DATABASE_POOL_TIMEOUT: 'The database pool did not provide a connection in time',
|
|
14
|
+
SERVICE_UNAVAILABLE: 'A required service was temporarily unavailable',
|
|
15
|
+
} as const;
|
|
16
|
+
|
|
17
|
+
export type DiagnosticReason = keyof typeof diagnosticMessages;
|
|
18
|
+
export type DiagnosticSeverity = 'error' | 'warning';
|
|
19
|
+
export type DiagnosticSource = 'request' | 'job' | 'operation';
|
|
20
|
+
export interface DiagnosticFrame { file: string; line: number | null; function: string | null }
|
|
21
|
+
export interface DiagnosticContext { severity: DiagnosticSeverity; source: DiagnosticSource; label: string }
|
|
22
|
+
export interface DiagnosticSample extends DiagnosticContext {
|
|
23
|
+
groupId: string;
|
|
24
|
+
code: string | null;
|
|
25
|
+
message: string;
|
|
26
|
+
frames: DiagnosticFrame[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const serverRoot = fileURLToPath(new URL('../../../', import.meta.url));
|
|
30
|
+
const dependencyCodes = new Map<string, DiagnosticReason>([
|
|
31
|
+
['ETIMEDOUT', 'DEPENDENCY_TIMEOUT'], ['ECONNABORTED', 'DEPENDENCY_TIMEOUT'],
|
|
32
|
+
['ECONNREFUSED', 'DEPENDENCY_UNAVAILABLE'], ['ECONNRESET', 'DEPENDENCY_UNAVAILABLE'],
|
|
33
|
+
['ENOTFOUND', 'DEPENDENCY_UNAVAILABLE'], ['EAI_AGAIN', 'DEPENDENCY_UNAVAILABLE'],
|
|
34
|
+
['P1001', 'DATABASE_UNAVAILABLE'], ['P1017', 'DATABASE_UNAVAILABLE'], ['P2024', 'DATABASE_POOL_TIMEOUT'],
|
|
35
|
+
['SERVICE_UNAVAILABLE', 'SERVICE_UNAVAILABLE'],
|
|
36
|
+
]);
|
|
37
|
+
const outboundKinds = new Map<string, DiagnosticReason>([
|
|
38
|
+
['timeout', 'DEPENDENCY_TIMEOUT'], ['network', 'DEPENDENCY_UNAVAILABLE'],
|
|
39
|
+
['http', 'DEPENDENCY_HTTP_FAILURE'], ['too-large', 'DEPENDENCY_RESPONSE_LIMIT'],
|
|
40
|
+
['blocked', 'DEPENDENCY_TARGET_REJECTED'],
|
|
41
|
+
]);
|
|
42
|
+
const fallback: Record<DiagnosticSource, string> = {
|
|
43
|
+
request: 'Unexpected request failure', job: 'Unexpected job failure', operation: 'Unexpected operation failure',
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Drop the complete message header, including multiline messages. Accept
|
|
47
|
+
* only structured V8 frames under this app's src or dist directory. */
|
|
48
|
+
function applicationFrames(error: Error): DiagnosticFrame[] {
|
|
49
|
+
const stack = error.stack;
|
|
50
|
+
const header = `${Error.prototype.toString.call(error)}\n`;
|
|
51
|
+
if (!stack?.startsWith(header)) return [];
|
|
52
|
+
const frames: DiagnosticFrame[] = [];
|
|
53
|
+
for (const row of stack.slice(header.length, header.length + 4_096).split('\n')) {
|
|
54
|
+
const match = /^\s+at (?:(.*?) \()?(.+):(\d+):\d+\)?$/.exec(row);
|
|
55
|
+
if (!match) continue;
|
|
56
|
+
const [, name, location, line] = match;
|
|
57
|
+
let absolute: string;
|
|
58
|
+
try { absolute = location.startsWith('file:') ? fileURLToPath(location) : location; } catch { continue; }
|
|
59
|
+
if (!path.isAbsolute(absolute)) continue;
|
|
60
|
+
const file = path.relative(serverRoot, absolute).split(path.sep).join('/');
|
|
61
|
+
if (file.length > 180 || !/^(?:src|dist)\/(?:[\w.-]+\/)*[\w.-]+\.(?:ts|js)$/.test(file) ||
|
|
62
|
+
/\/modules\/diagnostics\/diagnostics\.(?:context|sample)\./.test(file)) continue;
|
|
63
|
+
const compiled = file.startsWith('dist/');
|
|
64
|
+
const functionName = name?.replace(/^async /, '');
|
|
65
|
+
frames.push({
|
|
66
|
+
file: compiled ? file.replace(/^dist\//, 'src/').replace(/\.js$/, '.ts') : file,
|
|
67
|
+
// Compiled line numbers do not refer to the source file without source maps.
|
|
68
|
+
line: compiled ? null : Number(line),
|
|
69
|
+
function: functionName && /^[\w.$<>]{1,100}$/.test(functionName) ? functionName : null,
|
|
70
|
+
});
|
|
71
|
+
if (frames.length === 4) break;
|
|
72
|
+
}
|
|
73
|
+
return frames;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Raw exception messages and arbitrary error codes never enter a stored row. */
|
|
77
|
+
export function diagnosticSample(context: DiagnosticContext, error?: unknown, reason?: DiagnosticReason): DiagnosticSample {
|
|
78
|
+
let code = reason && Object.hasOwn(diagnosticMessages, reason) ? reason : undefined;
|
|
79
|
+
let frames: DiagnosticFrame[] = [];
|
|
80
|
+
if (error instanceof Error) {
|
|
81
|
+
const { code: rawCode, kind } = error as Error & { code?: string; kind?: string };
|
|
82
|
+
code ??= (error.name === 'OutboundHttpError' && kind ? outboundKinds.get(kind) : undefined) ??
|
|
83
|
+
(rawCode ? dependencyCodes.get(rawCode) : undefined);
|
|
84
|
+
frames = applicationFrames(error);
|
|
85
|
+
}
|
|
86
|
+
const location = frames[0];
|
|
87
|
+
const groupId = createHash('sha256').update(JSON.stringify([
|
|
88
|
+
context.severity, context.source, context.label,
|
|
89
|
+
code ?? null, location?.file ?? null, location?.function ?? null,
|
|
90
|
+
])).digest('hex');
|
|
91
|
+
return { ...context, groupId, code: code ?? null, message: code ? diagnosticMessages[code] : fallback[context.source], frames };
|
|
92
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { DIAGNOSTIC_WINDOW_MS } from './diagnostics.collector.js';
|
|
3
|
+
|
|
4
|
+
const maxRange = 7 * 24 * 60 * 60_000;
|
|
5
|
+
const groupId = z.string().regex(/^[a-f0-9]{64}$/);
|
|
6
|
+
const boundary = z.iso.datetime({ offset: true }).transform((value) => new Date(value))
|
|
7
|
+
.pipe(z.date().min(new Date('1000-01-01T00:00:00Z')).max(new Date('9999-12-31T23:59:59.999Z')))
|
|
8
|
+
.refine((date) => +date % DIAGNOSTIC_WINDOW_MS === 0, 'Use five-minute boundaries');
|
|
9
|
+
const position = z.tuple([z.number().int().positive(), groupId]);
|
|
10
|
+
const cursor = z.string().max(160).regex(/^[a-zA-Z0-9_-]+$/).transform((value, ctx) => {
|
|
11
|
+
let parsed: unknown;
|
|
12
|
+
try { parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')); } catch { /* invalid cursor */ }
|
|
13
|
+
const result = position.safeParse(parsed);
|
|
14
|
+
if (result.success) return result.data;
|
|
15
|
+
ctx.addIssue({ code: 'custom', message: 'Invalid diagnostics cursor' });
|
|
16
|
+
return z.NEVER;
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
export const diagnosticsQuerySchema = z.strictObject({
|
|
20
|
+
from: boundary,
|
|
21
|
+
to: boundary,
|
|
22
|
+
severity: z.enum(['error', 'warning']).optional(),
|
|
23
|
+
groupId: groupId.optional(),
|
|
24
|
+
limit: z.string().regex(/^\d{1,3}$/).transform(Number).pipe(z.number().int().min(1).max(100)).default(20),
|
|
25
|
+
cursor: cursor.optional(),
|
|
26
|
+
}).superRefine(({ from, to }, ctx) => {
|
|
27
|
+
if (!(from instanceof Date) || !(to instanceof Date)) return;
|
|
28
|
+
if (+to - +from <= 0 || +to - +from > maxRange) {
|
|
29
|
+
ctx.addIssue({ code: 'custom', path: ['to'], message: 'The interval must be positive and at most seven days' });
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
export type DiagnosticsQuery = z.output<typeof diagnosticsQuerySchema>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { FastifyInstance } from 'fastify';
|
|
2
|
+
import { env } from '@config/env.js';
|
|
3
|
+
import { logger } from '@libs/logger.js';
|
|
4
|
+
import { DiagnosticCollector } from './diagnostics.collector.js';
|
|
5
|
+
import { bindDiagnostics } from './diagnostics.context.js';
|
|
6
|
+
import { persistDiagnosticBuckets } from './diagnostics.repo.js';
|
|
7
|
+
|
|
8
|
+
/** Run the writer outside request and job scopes. Its own failures are
|
|
9
|
+
* operational logs only, which avoids feeding an outage back into the queue. */
|
|
10
|
+
export function registerDiagnostics(app: FastifyInstance): void {
|
|
11
|
+
const commit = env.SOURCE_COMMIT?.trim();
|
|
12
|
+
const collector = new DiagnosticCollector(persistDiagnosticBuckets, {
|
|
13
|
+
release: commit && /^[a-f0-9]{7,64}$/i.test(commit) ? commit.toLowerCase() : null,
|
|
14
|
+
});
|
|
15
|
+
bindDiagnostics(app, collector);
|
|
16
|
+
let failing = false;
|
|
17
|
+
const timer = setInterval(() => {
|
|
18
|
+
void collector.flush().then(() => { failing = false; }, () => {
|
|
19
|
+
if (!failing) logger.warn('[DIAGNOSTICS] Storage unavailable. Pending contributions will be retried.');
|
|
20
|
+
failing = true;
|
|
21
|
+
});
|
|
22
|
+
}, 15_000);
|
|
23
|
+
timer.unref();
|
|
24
|
+
|
|
25
|
+
app.addHook('onClose', async () => {
|
|
26
|
+
clearInterval(timer);
|
|
27
|
+
const stop = new AbortController();
|
|
28
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
29
|
+
try {
|
|
30
|
+
await Promise.race([
|
|
31
|
+
collector.close(stop.signal),
|
|
32
|
+
new Promise<never>((_resolve, reject) => {
|
|
33
|
+
// Leave time for the optional metrics flush and infrastructure cleanup.
|
|
34
|
+
timeout = setTimeout(() => { stop.abort(); reject(new Error('Diagnostics flush deadline')); }, 2_000);
|
|
35
|
+
}),
|
|
36
|
+
]);
|
|
37
|
+
} catch {
|
|
38
|
+
logger.warn('[DIAGNOSTICS] Pending contributions could not be flushed before shutdown');
|
|
39
|
+
} finally {
|
|
40
|
+
clearTimeout(timeout);
|
|
41
|
+
if (collector.droppedSamples) logger.warn({ droppedSamples: collector.droppedSamples }, '[DIAGNOSTICS] Buffer limit reached');
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useCallback, useRef, useState } from 'react';
|
|
4
|
+
import { useReportWebVitals } from 'next/web-vitals';
|
|
5
|
+
import { env } from '@/lib/env';
|
|
6
|
+
import { metricsPageGroup } from './metrics.pages';
|
|
7
|
+
|
|
8
|
+
export function WebVitalsReporter(): null {
|
|
9
|
+
// Web Vitals describe a document visit. A subsequent SPA navigation must
|
|
10
|
+
// not relabel an earlier navigation's LCP or interaction measurements.
|
|
11
|
+
const [visit] = useState(() => typeof window === 'undefined' ? null : {
|
|
12
|
+
page: metricsPageGroup(window.location.pathname),
|
|
13
|
+
sampled: Math.random() < env.NEXT_PUBLIC_METRICS_SAMPLE_RATE,
|
|
14
|
+
});
|
|
15
|
+
const seen = useRef(new Set<string>());
|
|
16
|
+
const send = useCallback<Parameters<typeof useReportWebVitals>[0]>(({ name, value }) => {
|
|
17
|
+
if (!visit?.sampled || (name !== 'LCP' && name !== 'INP' && name !== 'CLS')) return;
|
|
18
|
+
// React may replay the observer effect and create a new ID for the same
|
|
19
|
+
// navigation. Count each vital once per document, including bfcache restores.
|
|
20
|
+
if (seen.current.has(name)) return;
|
|
21
|
+
seen.current.add(name);
|
|
22
|
+
|
|
23
|
+
// Anonymous, best-effort delivery: skip the credentialed client and its
|
|
24
|
+
// refresh/retry hooks. Retrying an uncertain send would double count.
|
|
25
|
+
void fetch(`${env.NEXT_PUBLIC_API_BASE_URL.replace(/\/$/, '')}/metrics/web-vitals`, {
|
|
26
|
+
method: 'POST',
|
|
27
|
+
headers: { 'Content-Type': 'application/json' },
|
|
28
|
+
credentials: 'omit',
|
|
29
|
+
// Same-origin submissions can otherwise send the page, including its query.
|
|
30
|
+
referrerPolicy: 'no-referrer',
|
|
31
|
+
keepalive: true,
|
|
32
|
+
body: JSON.stringify({ page: visit.page, samples: [{ kind: name.toLowerCase(), value }] }),
|
|
33
|
+
}).catch(() => {});
|
|
34
|
+
}, [visit]);
|
|
35
|
+
useReportWebVitals(send);
|
|
36
|
+
return null;
|
|
37
|
+
}
|