a2host/public/js/validators.js

147 lines
4.3 KiB
JavaScript

/**
* a2host - Input Validators (ES Module)
* Validaciones estandarizadas en cliente para subdominios, puertos reservados y credenciales.
*/
export const RESERVED_PORTS_MAP = {
22: 'SSH (Acceso Remoto al Sistema)',
80: 'HTTP (Apache2 Web Server)',
443: 'HTTPS (Apache2 SSL/TLS)',
3000: 'Gitea (Servidor Git Privado)',
3005: 'a2host (Panel de Control Principal)',
3306: 'MySQL / MariaDB',
5101: 'Servicio Reservado del Sistema',
5432: 'PostgreSQL Database'
};
export const RESERVED_PORTS = Object.keys(RESERVED_PORTS_MAP).map(Number);
/**
* Valida el nombre de un subdominio según estándares RFC 1035 y reglas del sistema
* @param {string} name
* @returns {{ valid: boolean, error?: string, normalized: string }}
*/
export function validateSubdomainName(name) {
if (!name || typeof name !== 'string') {
return { valid: false, error: 'El nombre del subdominio es obligatorio', normalized: '' };
}
const trimmed = name.trim();
const normalized = trimmed.toLowerCase();
if (normalized.length === 0) {
return { valid: false, error: 'El nombre no puede estar vacío', normalized: '' };
}
if (normalized.length > 63) {
return {
valid: false,
error: `La longitud máxima es de 63 caracteres (actual: ${normalized.length})`,
normalized
};
}
if (normalized.startsWith('-') || normalized.endsWith('-')) {
return {
valid: false,
error: 'El nombre no puede iniciar ni terminar con un guión',
normalized
};
}
const regex = /^[a-z0-9-]+$/;
if (!regex.test(normalized)) {
return {
valid: false,
error: 'Solo se permiten letras minúsculas, números y guiones (^[a-z0-9-]+$)',
normalized
};
}
return { valid: true, normalized };
}
/**
* Valida el puerto TCP para Proxy Inverso (Modo B)
* @param {number|string} port
* @param {Array<{ name: string, port?: number }>} [existingSubdomains=[]]
* @param {string} [currentSubdomainName='']
* @returns {{ valid: boolean, error?: string, numPort?: number }}
*/
export function validatePort(port, existingSubdomains = [], currentSubdomainName = '') {
if (port === undefined || port === null || port === '') {
return { valid: false, error: 'El número de puerto es obligatorio en Modo B' };
}
const num = Number(port);
if (!Number.isInteger(num)) {
return { valid: false, error: 'El puerto debe ser un número entero' };
}
if (RESERVED_PORTS.includes(num)) {
const desc = RESERVED_PORTS_MAP[num] || 'Servicio Crítico del VPS';
return {
valid: false,
error: `El puerto ${num} está reservado estrictamente por el sistema (${desc}). Elija otro puerto libre.`
};
}
if (num < 1024 || num > 65535) {
return {
valid: false,
error: 'El puerto debe estar comprendido en el rango no privilegiado [1024 - 65535]'
};
}
// Verificar si otro subdominio ya usa este puerto
if (Array.isArray(existingSubdomains)) {
const conflict = existingSubdomains.find(
s => s.port === num && s.name !== currentSubdomainName
);
if (conflict) {
return {
valid: false,
error: `El puerto ${num} ya está asignado al subdominio '${conflict.name}'. Debe ser único.`
};
}
}
return { valid: true, numPort: num };
}
/**
* Valida un nombre de usuario
* @param {string} username
* @returns {{ valid: boolean, error?: string }}
*/
export function validateUsername(username) {
if (!username || typeof username !== 'string') {
return { valid: false, error: 'El nombre de usuario es obligatorio' };
}
const trimmed = username.trim();
if (trimmed.length < 3 || trimmed.length > 32) {
return { valid: false, error: 'El usuario debe tener entre 3 y 32 caracteres' };
}
if (!/^[a-zA-Z0-9_-]+$/.test(trimmed)) {
return { valid: false, error: 'Solo se permiten caracteres alfanuméricos, guiones y guiones bajos' };
}
return { valid: true };
}
/**
* Valida una contraseña
* @param {string} password
* @param {boolean} [allowEmpty=false]
* @returns {{ valid: boolean, error?: string }}
*/
export function validatePassword(password, allowEmpty = false) {
if (allowEmpty && (!password || password.length === 0)) {
return { valid: true };
}
if (!password || password.length < 8) {
return { valid: false, error: 'La contraseña debe contener al menos 8 caracteres' };
}
return { valid: true };
}