Refactor security functions

This commit is contained in:
gpt-engineer-app[bot]
2025-10-14 19:38:36 +00:00
parent 1554254c82
commit 95972a0b22
9 changed files with 638 additions and 89 deletions

View File

@@ -11,6 +11,7 @@ import type {
IdentitySafetyCheck,
IdentityOperationResult
} from '@/types/identity';
import { logger } from './logger';
/**
* Get all identities for the current user
@@ -23,7 +24,10 @@ export async function getUserIdentities(): Promise<UserIdentity[]> {
return (data?.identities || []) as UserIdentity[];
} catch (error: any) {
console.error('[IdentityService] Failed to get identities:', error);
logger.error('Failed to get user identities', {
action: 'get_identities',
error: error.message
});
return [];
}
}
@@ -124,7 +128,11 @@ export async function disconnectIdentity(
return { success: true };
} catch (error: any) {
console.error('[IdentityService] Failed to disconnect identity:', error);
logger.error('Failed to disconnect identity', {
action: 'identity_disconnect',
provider,
error: error.message
});
return {
success: false,
error: error.message || 'Failed to disconnect identity'
@@ -152,7 +160,11 @@ export async function connectIdentity(
return { success: true };
} catch (error: any) {
console.error('[IdentityService] Failed to connect identity:', error);
logger.error('Failed to connect identity', {
action: 'identity_connect',
provider,
error: error.message
});
return {
success: false,
error: error.message || `Failed to connect ${provider} account`
@@ -177,7 +189,10 @@ export async function addPasswordToAccount(): Promise<IdentityOperationResult> {
};
}
console.log('[IdentityService] Sending password reset email');
logger.info('Initiating password setup', {
action: 'password_setup_initiated',
email: userEmail
});
// Trigger Supabase password reset email
// User clicks link and sets password, which automatically creates email identity
@@ -189,11 +204,19 @@ export async function addPasswordToAccount(): Promise<IdentityOperationResult> {
);
if (resetError) {
console.error('[IdentityService] Failed to send password reset email:', resetError);
logger.error('Failed to send password reset email', {
userId: user?.id,
action: 'password_setup_email',
error: resetError.message
});
throw resetError;
}
console.log('[IdentityService] Password reset email sent successfully');
logger.info('Password reset email sent', {
userId: user!.id,
action: 'password_setup_initiated',
email: userEmail
});
// Log the action
await logIdentityChange(user!.id, 'password_setup_initiated', {
@@ -207,7 +230,10 @@ export async function addPasswordToAccount(): Promise<IdentityOperationResult> {
email: userEmail
};
} catch (error: any) {
console.error('[IdentityService] Failed to initiate password setup:', error);
logger.error('Failed to initiate password setup', {
action: 'password_setup',
error: error.message
});
return {
success: false,
error: error.message || 'Failed to send password reset email'
@@ -232,7 +258,11 @@ async function logIdentityChange(
_details: details
});
} catch (error) {
console.error('[IdentityService] Failed to log audit event:', error);
logger.error('Failed to log identity change to audit', {
userId,
action,
error: error instanceof Error ? error.message : String(error)
});
// Don't fail the operation if audit logging fails
}
}

View File

@@ -0,0 +1,92 @@
import { z } from 'zod';
import type { SecurityOperation } from '@/types/auth';
import type { UserRole } from '@/hooks/useUserRole';
/**
* Validation schemas for security operations
*/
export const sessionRevocationSchema = z.object({
sessionId: z.string().uuid('Invalid session ID'),
requiresConfirmation: z.boolean().default(true),
});
export const identityOperationSchema = z.object({
provider: z.enum(['google', 'discord']),
redirectTo: z.string().url().optional(),
});
export const mfaOperationSchema = z.object({
factorId: z.string().uuid('Invalid factor ID').optional(),
code: z.string().length(6, 'Code must be 6 digits').regex(/^\d+$/, 'Code must be numeric').optional(),
});
export const passwordChangeSchema = z.object({
currentPassword: z.string().min(1, 'Current password required'),
newPassword: z.string()
.min(8, 'Must be at least 8 characters')
.max(128, 'Must be less than 128 characters')
.regex(/[A-Z]/, 'Must contain uppercase letter')
.regex(/[a-z]/, 'Must contain lowercase letter')
.regex(/[0-9]/, 'Must contain number')
.regex(/[^A-Za-z0-9]/, 'Must contain special character'),
confirmPassword: z.string(),
captchaToken: z.string().min(1, 'CAPTCHA verification required'),
}).refine(data => data.newPassword === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"]
});
/**
* Determines if an operation requires CAPTCHA verification
*/
export function requiresCaptcha(operation: SecurityOperation): boolean {
const captchaOperations: SecurityOperation[] = [
'password_change',
'identity_disconnect',
'mfa_unenroll'
];
return captchaOperations.includes(operation);
}
/**
* Determines if an operation requires MFA verification for the user's role
*/
export function requiresMFA(
operation: SecurityOperation,
userRoles: UserRole[]
): boolean {
const privilegedRoles: UserRole[] = ['moderator', 'admin', 'superuser'];
const hasPrivilegedRole = userRoles.some(role => privilegedRoles.includes(role));
if (!hasPrivilegedRole) return false;
// MFA required for these operations if user is privileged
const mfaOperations: SecurityOperation[] = [
'password_change',
'session_revoke',
'mfa_unenroll'
];
return mfaOperations.includes(operation);
}
/**
* Get rate limit parameters for a security operation
*/
export function getRateLimitParams(operation: SecurityOperation): {
action: string;
maxAttempts: number;
windowMinutes: number;
} {
const limits: Record<SecurityOperation, { action: string; maxAttempts: number; windowMinutes: number }> = {
password_change: { action: 'password_change', maxAttempts: 3, windowMinutes: 60 },
identity_disconnect: { action: 'identity_disconnect', maxAttempts: 3, windowMinutes: 60 },
identity_connect: { action: 'identity_connect', maxAttempts: 5, windowMinutes: 60 },
session_revoke: { action: 'session_revoke', maxAttempts: 10, windowMinutes: 60 },
mfa_enroll: { action: 'mfa_enroll', maxAttempts: 3, windowMinutes: 60 },
mfa_unenroll: { action: 'mfa_unenroll', maxAttempts: 2, windowMinutes: 60 },
};
return limits[operation] || { action: operation, maxAttempts: 5, windowMinutes: 60 };
}