mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
refactor: eslint and prettier conflict will be resolved and formatted
This commit is contained in:
@@ -6,9 +6,9 @@ export const { GET } = handlers;
|
||||
|
||||
// Wrap NextAuth POST with login rate limiting
|
||||
export async function POST(request: Request) {
|
||||
const limited = await rateLimit(request, 'login');
|
||||
if (limited) return limited;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const response = await handlers.POST(request as any);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
const limited = await rateLimit(request, 'login');
|
||||
if (limited) return limited;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const response = await handlers.POST(request as any);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
}
|
||||
|
||||
+146
-138
@@ -2,149 +2,157 @@ import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { acceptInvitationTokenForUser, getValidInvitationByToken } from '@/lib/invitations';
|
||||
import { checkRateLimit, getClientIp, rateLimitHeaders, RATE_LIMIT_CONFIGS } from '@/lib/rate-limit';
|
||||
import {
|
||||
checkRateLimit,
|
||||
getClientIp,
|
||||
rateLimitHeaders,
|
||||
RATE_LIMIT_CONFIGS,
|
||||
} from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { isInviteCodeRequired } from '@/lib/feature-flags';
|
||||
import { logError } from '@/lib/logger';
|
||||
import { createVerificationToken, isEmailVerificationEnabled, sendVerificationEmail } from '@/lib/email-verification';
|
||||
import {
|
||||
createVerificationToken,
|
||||
isEmailVerificationEnabled,
|
||||
sendVerificationEmail,
|
||||
} from '@/lib/email-verification';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
// Rate limiting by IP
|
||||
const clientIp = getClientIp(request);
|
||||
const rateLimitKey = `register:${clientIp}`;
|
||||
const rateLimit = await checkRateLimit(rateLimitKey, 'register');
|
||||
try {
|
||||
// Rate limiting by IP
|
||||
const clientIp = getClientIp(request);
|
||||
const rateLimitKey = `register:${clientIp}`;
|
||||
const rateLimit = await checkRateLimit(rateLimitKey, 'register');
|
||||
|
||||
if (!rateLimit.allowed) {
|
||||
return apiErrors.rateLimited('Too many registration attempts. Please try again later.');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, email, password, inviteCode, invitationToken } = body;
|
||||
|
||||
// Validate required fields
|
||||
if (!name || typeof name !== 'string' || name.trim().length < 2 || name.trim().length > 100) {
|
||||
return apiErrors.badRequest('Name must be between 2 and 100 characters');
|
||||
}
|
||||
|
||||
if (!email || typeof email !== 'string') {
|
||||
return apiErrors.badRequest('Email is required');
|
||||
}
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.validationError('Invalid email format');
|
||||
}
|
||||
|
||||
// Allow registration via a valid invitation token OR global invite code.
|
||||
let invitationIsValid = false;
|
||||
let validatedInvitationToken: string | null = null;
|
||||
if (typeof invitationToken === 'string' && invitationToken.trim()) {
|
||||
const normalizedToken = invitationToken.trim();
|
||||
const invitation = await getValidInvitationByToken(normalizedToken);
|
||||
if (invitation && invitation.email === normalizedEmail) {
|
||||
invitationIsValid = true;
|
||||
validatedInvitationToken = normalizedToken;
|
||||
} else {
|
||||
return apiErrors.forbidden('Invalid or expired invitation token');
|
||||
}
|
||||
}
|
||||
|
||||
if (!invitationIsValid && isInviteCodeRequired()) {
|
||||
// Validate invite code using constant-time comparison to prevent timing attacks
|
||||
const validInviteCode = process.env.INVITE_CODE;
|
||||
if (!validInviteCode || !inviteCode) {
|
||||
return apiErrors.forbidden('Invalid invite code');
|
||||
}
|
||||
|
||||
// Constant-time comparison
|
||||
const { timingSafeEqual } = await import('crypto');
|
||||
const validBuffer = Buffer.from(validInviteCode);
|
||||
const providedBuffer = Buffer.from(String(inviteCode));
|
||||
|
||||
// Ensure same length for comparison (prevents length-based timing leak)
|
||||
const isValidLength = validBuffer.length === providedBuffer.length;
|
||||
const compareBuffer = isValidLength ? providedBuffer : validBuffer;
|
||||
const isValidCode = isValidLength && timingSafeEqual(validBuffer, compareBuffer);
|
||||
|
||||
if (!isValidCode) {
|
||||
return apiErrors.forbidden('Invalid invite code');
|
||||
}
|
||||
}
|
||||
|
||||
if (!password || typeof password !== 'string' || password.length < 8 || password.length > 128) {
|
||||
return apiErrors.badRequest('Password must be between 8 and 128 characters');
|
||||
}
|
||||
|
||||
// Check if email already exists
|
||||
const existingUser = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
return apiErrors.conflict('An account with this email already exists');
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(password, 12);
|
||||
|
||||
// If SMTP is not configured, auto-verify the email so users aren't locked out
|
||||
const emailVerificationRequired = isEmailVerificationEnabled();
|
||||
|
||||
// Create user
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
email: normalizedEmail,
|
||||
password: hashedPassword,
|
||||
emailVerified: emailVerificationRequired ? null : new Date(),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (validatedInvitationToken) {
|
||||
const result = await acceptInvitationTokenForUser({
|
||||
token: validatedInvitationToken,
|
||||
userId: user.id,
|
||||
email: normalizedEmail,
|
||||
});
|
||||
if (result !== 'accepted') {
|
||||
await db.user.delete({ where: { id: user.id } });
|
||||
return apiErrors.conflict('Invitation could not be accepted. Please request a new invitation.');
|
||||
}
|
||||
}
|
||||
|
||||
// Send verification email if SMTP is configured
|
||||
if (emailVerificationRequired) {
|
||||
const verificationToken = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, verificationToken);
|
||||
}
|
||||
|
||||
const message = emailVerificationRequired
|
||||
? 'Account created. Please check your email to verify your address before signing in.'
|
||||
: 'Account created successfully';
|
||||
|
||||
const response = successResponse(
|
||||
{ message, user, emailVerificationRequired },
|
||||
201
|
||||
);
|
||||
|
||||
// Add rate limit headers to successful response
|
||||
const headers = rateLimitHeaders(rateLimit, RATE_LIMIT_CONFIGS.register.maxRequests);
|
||||
Object.entries(headers).forEach(([key, value]) => {
|
||||
response.headers.set(key, value);
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Registration error:', error);
|
||||
return apiErrors.internalError('Failed to create account');
|
||||
if (!rateLimit.allowed) {
|
||||
return apiErrors.rateLimited('Too many registration attempts. Please try again later.');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, email, password, inviteCode, invitationToken } = body;
|
||||
|
||||
// Validate required fields
|
||||
if (!name || typeof name !== 'string' || name.trim().length < 2 || name.trim().length > 100) {
|
||||
return apiErrors.badRequest('Name must be between 2 and 100 characters');
|
||||
}
|
||||
|
||||
if (!email || typeof email !== 'string') {
|
||||
return apiErrors.badRequest('Email is required');
|
||||
}
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.validationError('Invalid email format');
|
||||
}
|
||||
|
||||
// Allow registration via a valid invitation token OR global invite code.
|
||||
let invitationIsValid = false;
|
||||
let validatedInvitationToken: string | null = null;
|
||||
if (typeof invitationToken === 'string' && invitationToken.trim()) {
|
||||
const normalizedToken = invitationToken.trim();
|
||||
const invitation = await getValidInvitationByToken(normalizedToken);
|
||||
if (invitation && invitation.email === normalizedEmail) {
|
||||
invitationIsValid = true;
|
||||
validatedInvitationToken = normalizedToken;
|
||||
} else {
|
||||
return apiErrors.forbidden('Invalid or expired invitation token');
|
||||
}
|
||||
}
|
||||
|
||||
if (!invitationIsValid && isInviteCodeRequired()) {
|
||||
// Validate invite code using constant-time comparison to prevent timing attacks
|
||||
const validInviteCode = process.env.INVITE_CODE;
|
||||
if (!validInviteCode || !inviteCode) {
|
||||
return apiErrors.forbidden('Invalid invite code');
|
||||
}
|
||||
|
||||
// Constant-time comparison
|
||||
const { timingSafeEqual } = await import('crypto');
|
||||
const validBuffer = Buffer.from(validInviteCode);
|
||||
const providedBuffer = Buffer.from(String(inviteCode));
|
||||
|
||||
// Ensure same length for comparison (prevents length-based timing leak)
|
||||
const isValidLength = validBuffer.length === providedBuffer.length;
|
||||
const compareBuffer = isValidLength ? providedBuffer : validBuffer;
|
||||
const isValidCode = isValidLength && timingSafeEqual(validBuffer, compareBuffer);
|
||||
|
||||
if (!isValidCode) {
|
||||
return apiErrors.forbidden('Invalid invite code');
|
||||
}
|
||||
}
|
||||
|
||||
if (!password || typeof password !== 'string' || password.length < 8 || password.length > 128) {
|
||||
return apiErrors.badRequest('Password must be between 8 and 128 characters');
|
||||
}
|
||||
|
||||
// Check if email already exists
|
||||
const existingUser = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
return apiErrors.conflict('An account with this email already exists');
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(password, 12);
|
||||
|
||||
// If SMTP is not configured, auto-verify the email so users aren't locked out
|
||||
const emailVerificationRequired = isEmailVerificationEnabled();
|
||||
|
||||
// Create user
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
email: normalizedEmail,
|
||||
password: hashedPassword,
|
||||
emailVerified: emailVerificationRequired ? null : new Date(),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (validatedInvitationToken) {
|
||||
const result = await acceptInvitationTokenForUser({
|
||||
token: validatedInvitationToken,
|
||||
userId: user.id,
|
||||
email: normalizedEmail,
|
||||
});
|
||||
if (result !== 'accepted') {
|
||||
await db.user.delete({ where: { id: user.id } });
|
||||
return apiErrors.conflict(
|
||||
'Invitation could not be accepted. Please request a new invitation.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Send verification email if SMTP is configured
|
||||
if (emailVerificationRequired) {
|
||||
const verificationToken = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, verificationToken);
|
||||
}
|
||||
|
||||
const message = emailVerificationRequired
|
||||
? 'Account created. Please check your email to verify your address before signing in.'
|
||||
: 'Account created successfully';
|
||||
|
||||
const response = successResponse({ message, user, emailVerificationRequired }, 201);
|
||||
|
||||
// Add rate limit headers to successful response
|
||||
const headers = rateLimitHeaders(rateLimit, RATE_LIMIT_CONFIGS.register.maxRequests);
|
||||
Object.entries(headers).forEach(([key, value]) => {
|
||||
response.headers.set(key, value);
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
logError('Registration error:', error);
|
||||
return apiErrors.internalError('Failed to create account');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,54 +2,63 @@ import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { createVerificationToken, isEmailVerificationEnabled, sendVerificationEmail } from '@/lib/email-verification';
|
||||
import {
|
||||
createVerificationToken,
|
||||
isEmailVerificationEnabled,
|
||||
sendVerificationEmail,
|
||||
} from '@/lib/email-verification';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
if (!isEmailVerificationEnabled()) {
|
||||
return apiErrors.badRequest('Email verification is not enabled');
|
||||
}
|
||||
|
||||
// Rate-limit by IP to prevent abuse
|
||||
const clientIp = getClientIp(request);
|
||||
const rateLimitResult = await checkRateLimit(`resend-verification:${clientIp}`, 'resend-verification');
|
||||
if (!rateLimitResult.allowed) {
|
||||
return apiErrors.rateLimited('Too many requests. Please try again later.');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { email } = body;
|
||||
|
||||
if (!email || typeof email !== 'string' || email.length > 254 || !email.includes('@')) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
// Look up user — return a generic success regardless of whether the email
|
||||
// exists to avoid user enumeration
|
||||
const user = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true, emailVerified: true },
|
||||
});
|
||||
|
||||
if (user && !user.emailVerified) {
|
||||
const token = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, token);
|
||||
}
|
||||
|
||||
return withCacheControl(
|
||||
successResponse({ message: 'If that email has an unverified account, a new verification link has been sent.' }),
|
||||
'private, no-store'
|
||||
);
|
||||
} catch (err) {
|
||||
logError('Resend verification error:', err);
|
||||
return apiErrors.internalError('Failed to resend verification email');
|
||||
try {
|
||||
if (!isEmailVerificationEnabled()) {
|
||||
return apiErrors.badRequest('Email verification is not enabled');
|
||||
}
|
||||
|
||||
// Rate-limit by IP to prevent abuse
|
||||
const clientIp = getClientIp(request);
|
||||
const rateLimitResult = await checkRateLimit(
|
||||
`resend-verification:${clientIp}`,
|
||||
'resend-verification'
|
||||
);
|
||||
if (!rateLimitResult.allowed) {
|
||||
return apiErrors.rateLimited('Too many requests. Please try again later.');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { email } = body;
|
||||
|
||||
if (!email || typeof email !== 'string' || email.length > 254 || !email.includes('@')) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
// Look up user — return a generic success regardless of whether the email
|
||||
// exists to avoid user enumeration
|
||||
const user = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true, emailVerified: true },
|
||||
});
|
||||
|
||||
if (user && !user.emailVerified) {
|
||||
const token = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, token);
|
||||
}
|
||||
|
||||
return withCacheControl(
|
||||
successResponse({
|
||||
message: 'If that email has an unverified account, a new verification link has been sent.',
|
||||
}),
|
||||
'private, no-store'
|
||||
);
|
||||
} catch (err) {
|
||||
logError('Resend verification error:', err);
|
||||
return apiErrors.internalError('Failed to resend verification email');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,26 +7,26 @@ import { logError } from '@/lib/logger';
|
||||
const TOKEN_REGEX = /^[0-9a-f]{64}$/;
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// Rate-limit by IP to prevent token enumeration attacks.
|
||||
const limited = await rateLimit(request, 'verify-email');
|
||||
if (limited) return limited;
|
||||
try {
|
||||
// Rate-limit by IP to prevent token enumeration attacks.
|
||||
const limited = await rateLimit(request, 'verify-email');
|
||||
if (limited) return limited;
|
||||
|
||||
const token = request.nextUrl.searchParams.get('token');
|
||||
const token = request.nextUrl.searchParams.get('token');
|
||||
|
||||
if (!token || !TOKEN_REGEX.test(token.trim())) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
const email = await consumeVerificationToken(token.trim());
|
||||
|
||||
if (!email) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL('/login?verified=true', request.url));
|
||||
} catch (err) {
|
||||
logError('Email verification error:', err);
|
||||
return NextResponse.redirect(new URL('/login?error=VerificationFailed', request.url));
|
||||
if (!token || !TOKEN_REGEX.test(token.trim())) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
const email = await consumeVerificationToken(token.trim());
|
||||
|
||||
if (!email) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL('/login?verified=true', request.url));
|
||||
} catch (err) {
|
||||
logError('Email verification error:', err);
|
||||
return NextResponse.redirect(new URL('/login?error=VerificationFailed', request.url));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user