1import type { RequestHandler } from '@sveltejs/kit';
2import type { RegisterResponseSuccess, RegisterResponseError } from '$lib/types/payloads';
3import { users } from '$lib/db/convex.server';
4import { hashPassword } from '$lib/utils/password';
5import { createRegistrationSchema, DEFAULT_PASSWORD_CONSTRAINTS } from '$lib/validation/password';
6import { createLogger } from '$lib/utils/logger.server';
7
8const log = createLogger('register-server');
9
10// In-memory map to track failed captcha attempts per IP
11const captchaAttempts = new Map<string, { count: number; lastAttempt: number }>();
12
13// Lazy cleanup of stale captcha attempts
14const ONE_HOUR = 60 * 60 * 1000;
15let lastCleanup = 0;
16function cleanupOldCaptchaAttempts() {
17 const now = Date.now();
18 if (now - lastCleanup < ONE_HOUR) return;
19 lastCleanup = now;
20
21 for (const [ip, data] of captchaAttempts.entries()) {
22 if (now - data.lastAttempt > ONE_HOUR) {
23 captchaAttempts.delete(ip);
24 }
25 }
26}
27
28export const POST: RequestHandler = async ({ request, getClientAddress }) => {
29 log.debug('New registration attempt received');
30
31 cleanupOldCaptchaAttempts();
32
33 if (request.method !== 'POST') {
34 log.warn('Invalid method used', { method: request.method });
35 return new Response(JSON.stringify({ error: 'Method Not Allowed' } as RegisterResponseError), {
36 status: 405
37 });
38 }
39
40 // Get the IP address for rate limiting and Turnstile validation
41 const ip = getClientAddress();
42 const maskedIp = ip
43 .split('.')
44 .map((octet, idx) => (idx < 3 ? 'xxx' : octet))
45 .join('.');
46 const now = Date.now();
47 const attemptData = captchaAttempts.get(ip) || { count: 0, lastAttempt: 0 };
48
49 let body: unknown;
50 try {
51 body = await request.json();
52 } catch {
53 log.warn('Invalid JSON payload received');
54 return new Response(JSON.stringify({ error: 'Invalid JSON' } as RegisterResponseError), {
55 status: 400
56 });
57 }
58
59 const { suUsername, suPassword, suConfirmPassword, captchaAnswer, turnstileToken } = body as {
60 suUsername: string;
61 suPassword: string;
62 suConfirmPassword: string;
63 captchaAnswer: string;
64 turnstileToken?: string;
65 };
66
67 // Validate input using Zod schema
68 try {
69 const registrationSchema = createRegistrationSchema(DEFAULT_PASSWORD_CONSTRAINTS);
70 registrationSchema.parse({
71 suUsername,
72 suPassword,
73 suConfirmPassword,
74 captchaAnswer,
75 turnstileToken
76 });
77 } catch (err: unknown) {
78 const zodError = err as { errors?: Array<{ message?: string }> };
79 const errorMessage = zodError.errors?.[0]?.message || 'Invalid input data';
80 log.warn('Registration validation failed', { error: errorMessage });
81 return new Response(JSON.stringify({ error: errorMessage } as RegisterResponseError), {
82 status: 400
83 });
84 }
85
86 // Validate PDR captcha
87 // SECURITY NOTE: Static CAPTCHA answer is intentional for this community app.
88 // The answer "point de rencontre" acts as a shared-knowledge gate, not bot prevention.
89 // Bot prevention is handled by Cloudflare Turnstile (when enabled in production).
90 const normalizedAnswer = captchaAnswer.trim().toLowerCase();
91 if (normalizedAnswer !== 'point de rencontre') {
92 attemptData.count++;
93 attemptData.lastAttempt = now;
94 captchaAttempts.set(ip, attemptData);
95 log.warn('Invalid captcha answer', { maskedIp, attemptCount: attemptData.count });
96 return new Response(
97 JSON.stringify({ error: 'Invalid answer to the PDR question' } as RegisterResponseError),
98 { status: 400 }
99 );
100 }
101
102 // Reset captcha attempts on success
103 captchaAttempts.delete(ip);
104
105 // Trim input values (validation already done by Zod)
106 const username = suUsername.trim();
107 const password = suPassword;
108
109 // Check if nickname already exists using Convex
110 const existingUser = await users.getByNickname(username);
111 if (existingUser) {
112 log.warn('Username already exists', { username });
113 return new Response(
114 JSON.stringify({ error: 'This username is already taken' } as RegisterResponseError),
115 { status: 409 }
116 );
117 }
118
119 // Securely hash the user's password.
120 let hashedPassword: string;
121 try {
122 hashedPassword = await hashPassword(password);
123 } catch {
124 log.error('Error hashing password');
125 return new Response(
126 JSON.stringify({ error: 'Internal Server Error' } as RegisterResponseError),
127 { status: 500 }
128 );
129 }
130
131 // Insert the new user into Convex
132 try {
133 await users.create(username, hashedPassword);
134 log.info(`User ${username} registered successfully`);
135 } catch (err: unknown) {
136 log.error('Database insertion error', { error: err as object });
137 return new Response(
138 JSON.stringify({
139 error: 'User registration failed. Possibly user already exists.'
140 } as RegisterResponseError),
141 { status: 409 }
142 );
143 }
144
145 return new Response(JSON.stringify({ success: true } as RegisterResponseSuccess), {
146 status: 201
147 });
148};