-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathvalidationUtils.ts
More file actions
234 lines (206 loc) · 5.75 KB
/
Copy pathvalidationUtils.ts
File metadata and controls
234 lines (206 loc) · 5.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/**
* Centralized Validation Utilities
*/
import type { PasswordValidationResult } from '../types/auth-types';
import { z } from 'zod';
/**
* Email validation configuration
*/
export interface EmailValidationConfig {
allowPlusAddressing?: boolean; // Allow email+tag@domain.com
allowInternational?: boolean; // Allow international domains
maxLength?: number; // Maximum email length
blockedDomains?: string[]; // Blocked email domains
}
/**
* Default email validation configuration
*/
const DEFAULT_EMAIL_CONFIG: EmailValidationConfig = {
allowPlusAddressing: true,
allowInternational: true,
maxLength: 254, // RFC 5321 limit
blockedDomains: ['10minutemail.com', 'tempmail.org'], // Add known temp email domains
};
/**
* Comprehensive email validation
*/
export function validateEmail(
email: string,
config: EmailValidationConfig = DEFAULT_EMAIL_CONFIG,
): { valid: boolean; error?: string } {
if (!email || typeof email !== 'string') {
return { valid: false, error: 'Email is required' };
}
// Length check
const maxLength = config.maxLength || DEFAULT_EMAIL_CONFIG.maxLength!;
if (email.length > maxLength) {
return {
valid: false,
error: `Email must be less than ${maxLength} characters`,
};
}
// Basic format validation
const emailRegex = config.allowInternational
? /^[^\s@]+@[^\s@]+\.[^\s@]+$/ // Basic international-friendly regex
: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; // ASCII only
if (!emailRegex.test(email)) {
return { valid: false, error: 'Invalid email format' };
}
// Domain validation
const domain = email.split('@')[1]?.toLowerCase();
if (config.blockedDomains?.includes(domain)) {
return { valid: false, error: 'Email domain is not allowed' };
}
// Plus addressing check (if disabled)
if (!config.allowPlusAddressing && email.includes('+')) {
return { valid: false, error: 'Plus addressing is not allowed' };
}
return { valid: true };
}
/**
* Zod schema for password validation
*/
const passwordSchema = z
.string()
.min(8, 'Password must be at least 8 characters')
.max(128, 'Password must be less than 128 characters')
.regex(/[a-z]/, 'Password must contain at least one lowercase letter')
.regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
.regex(/[0-9]/, 'Password must contain at least one number');
/**
* Password validation using Zod
*/
export function validatePassword(
password: string,
_config?: unknown,
_userInfo?: { email?: string; username?: string; name?: string },
): PasswordValidationResult {
if (!password || typeof password !== 'string') {
return {
valid: false,
errors: ['Password is required'],
score: 0,
requirements: {
minLength: false,
hasLowercase: false,
hasUppercase: false,
hasNumbers: false,
hasSpecialChars: false,
notCommon: false,
noSequential: false,
},
};
}
const result = passwordSchema.safeParse(password);
const requirements = {
minLength: password.length >= 8,
hasLowercase: /[a-z]/.test(password),
hasUppercase: /[A-Z]/.test(password),
hasNumbers: /[0-9]/.test(password),
hasSpecialChars: /[^a-zA-Z0-9]/.test(password),
notCommon: true,
noSequential: true,
};
// Calculate score based on strength
let score = 0;
if (requirements.minLength) score++;
if (requirements.hasLowercase && requirements.hasUppercase) score++;
if (requirements.hasNumbers) score++;
if (requirements.hasSpecialChars) score++;
if (password.length >= 12) score = Math.min(4, score + 1);
// Generate suggestions
const suggestions: string[] = [];
if (password.length < 12) {
suggestions.push('Use at least 12 characters for better security');
}
if (!requirements.hasSpecialChars) {
suggestions.push('Add special characters for enhanced security');
}
if (!result.success) {
return {
valid: false,
errors: result.error.issues.map(e => e.message),
score,
requirements,
suggestions: suggestions.length > 0 ? suggestions : undefined,
};
}
return {
valid: true,
score,
requirements,
suggestions: suggestions.length > 0 ? suggestions : undefined,
};
}
/**
* Validate username format
*/
export function validateUsername(
username: string,
config?: {
minLength?: number;
maxLength?: number;
allowSpecialChars?: boolean;
reservedNames?: string[];
},
): { valid: boolean; error?: string } {
const {
minLength = 3,
maxLength = 30,
allowSpecialChars = false,
reservedNames = ['admin', 'root', 'api', 'www', 'mail', 'support'],
} = config || {};
if (!username || typeof username !== 'string') {
return { valid: false, error: 'Username is required' };
}
if (username.length < minLength) {
return {
valid: false,
error: `Username must be at least ${minLength} characters`,
};
}
if (username.length > maxLength) {
return {
valid: false,
error: `Username must be less than ${maxLength} characters`,
};
}
// Format validation
const validPattern = allowSpecialChars
? /^[a-zA-Z0-9_.-]+$/
: /^[a-zA-Z0-9_]+$/;
if (!validPattern.test(username)) {
return {
valid: false,
error: allowSpecialChars
? 'Username can only contain letters, numbers, underscores, dots, and hyphens'
: 'Username can only contain letters, numbers, and underscores',
};
}
// Reserved names check
if (reservedNames.includes(username.toLowerCase())) {
return { valid: false, error: 'Username is reserved' };
}
// Must start with letter or number
if (!/^[a-zA-Z0-9]/.test(username)) {
return {
valid: false,
error: 'Username must start with a letter or number',
};
}
return { valid: true };
}
/**
* Batch validation utility
*/
export interface ValidationField<
T extends readonly unknown[] = readonly unknown[],
> {
value: string;
validator: (
value: string,
...args: T
) => { valid: boolean; error?: string };
validatorArgs?: T;
fieldName: string;
}