+server.ts RawHistoryFolder

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};

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 3

Tags 9

↑↓ moveenter openesc close