@axlotl-lab/navigrator
Version:
A powerful local domain manager for development environments. Navigrator helps you manage local domains and SSL certificates with a simple web interface.
382 lines (381 loc) • 17.3 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HostsManager = void 0;
const fs = __importStar(require("fs/promises"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
// Identificador único para los registros creados por nuestra aplicación
const APP_IDENTIFIER = '# @axlotl-lab/navigrator';
const DISABLED_IDENTIFIER = '# @axlotl-lab/navigrator-disabled';
class HostsManager {
constructor() {
// Determinar la ruta del archivo hosts según el sistema operativo
if (os.platform() === 'win32') {
this.hostsFilePath = path.join('C:', 'Windows', 'System32', 'drivers', 'etc', 'hosts');
}
else {
this.hostsFilePath = '/etc/hosts';
}
}
/**
* Lee el archivo hosts y devuelve todas las entradas
*/
readHosts() {
return __awaiter(this, void 0, void 0, function* () {
try {
const content = yield fs.readFile(this.hostsFilePath, 'utf-8');
return this.parseHostsFile(content);
}
catch (error) {
console.error('Error reading hosts file:', error);
throw new Error(`Failed to read hosts file: ${error === null || error === void 0 ? void 0 : error.message}`);
}
});
}
/**
* Lee solo las entradas locales (127.0.0.1 o ::1)
*/
readLocalHosts() {
return __awaiter(this, void 0, void 0, function* () {
const allHosts = yield this.readHosts();
return allHosts.filter(host => host.ip === '127.0.0.1' || host.ip === '::1');
});
}
/**
* Parsea el contenido del archivo hosts
*/
parseHostsFile(content) {
const lines = content.split('\n');
const entries = [];
for (let i = 0; i < lines.length; i++) {
let line = lines[i].trim();
let isDisabled = false;
// Detectar si la línea está comentada
if (line.startsWith('#')) {
// Verificar si es un dominio deshabilitado por nosotros
if (i < lines.length - 1 && lines[i + 1].trim() === DISABLED_IDENTIFIER) {
// Quitar el comentario para obtener la información de la línea
line = line.substring(1).trim();
isDisabled = true;
}
else if (line === APP_IDENTIFIER || line === DISABLED_IDENTIFIER) {
continue;
}
else {
continue; // Ignorar otros comentarios
}
}
// Ignorar líneas vacías
if (line === '')
continue;
// Verificar si la línea siguiente es nuestro identificador
const isCreatedByUs = (i < lines.length - 1 &&
(lines[i + 1].trim() === APP_IDENTIFIER || lines[i + 1].trim() === DISABLED_IDENTIFIER));
// Extraer IP y dominio
const parts = line.split(/\s+/);
if (parts.length >= 2) {
const ip = parts[0];
const domain = parts[1];
entries.push({
ip,
domain,
isCreatedByUs,
isDisabled,
lineNumber: i + 1
});
// Si esta entrada es nuestra, saltar la siguiente línea (que contiene el identificador)
if (isCreatedByUs)
i++;
}
}
return entries;
}
/**
* Agrega un nuevo registro al archivo hosts
*/
addHost(domain_1) {
return __awaiter(this, arguments, void 0, function* (domain, ip = '127.0.0.1') {
try {
// Verificar si el dominio ya existe
const hosts = yield this.readHosts();
const existingHost = hosts.find(h => h.domain === domain && h.ip === ip);
if (existingHost) {
if (existingHost.isCreatedByUs) {
if (existingHost.isDisabled) {
// Si está deshabilitado, lo habilitamos
return yield this.toggleHostState(domain, false);
}
return true; // Ya existe y está habilitado, no hacer nada
}
else {
// Existe pero no fue creado por nosotros, marcar como nuestro
return yield this.markHostAsOurs(domain, ip);
}
}
// Agregar nuevo host
const newEntry = `\n${ip} ${domain}\n${APP_IDENTIFIER}`;
return yield this.appendToHostsFile(newEntry);
}
catch (error) {
console.error('Error adding host:', error);
throw new Error(`Failed to add host: ${error === null || error === void 0 ? void 0 : error.message}`);
}
});
}
/**
* "Adopta" un dominio existente marcándolo como creado por nuestra aplicación
*/
adoptHost(domain_1) {
return __awaiter(this, arguments, void 0, function* (domain, ip = '127.0.0.1') {
return yield this.markHostAsOurs(domain, ip);
});
}
/**
* Importa todos los dominios locales existentes y los marca como nuestros
*/
importAllLocalHosts() {
return __awaiter(this, void 0, void 0, function* () {
try {
const hosts = yield this.readLocalHosts();
const hostsToAdopt = hosts.filter(host => !host.isCreatedByUs);
let adoptedCount = 0;
for (const host of hostsToAdopt) {
const success = yield this.adoptHost(host.domain, host.ip);
if (success)
adoptedCount++;
}
return {
success: adoptedCount > 0,
count: adoptedCount
};
}
catch (error) {
console.error('Error importing all hosts:', error);
throw new Error(`Failed to import hosts: ${error === null || error === void 0 ? void 0 : error.message}`);
}
});
}
/**
* Marca un host existente como creado por nuestra aplicación
*/
markHostAsOurs(domain, ip) {
return __awaiter(this, void 0, void 0, function* () {
try {
const content = yield fs.readFile(this.hostsFilePath, 'utf-8');
const lines = content.split('\n');
let modified = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line === '' || line.startsWith('#'))
continue;
const parts = line.split(/\s+/);
if (parts.length >= 2 && parts[0] === ip && parts[1] === domain) {
// Verificar si la siguiente línea ya es nuestro identificador
if (i < lines.length - 1 &&
(lines[i + 1].trim() === APP_IDENTIFIER || lines[i + 1].trim() === DISABLED_IDENTIFIER)) {
return true; // Ya está marcado
}
// Insertar identificador después de esta línea
lines.splice(i + 1, 0, APP_IDENTIFIER);
modified = true;
break;
}
}
if (modified) {
return yield this.writeHostsFile(lines.join('\n'));
}
return false;
}
catch (error) {
console.error('Error marking host as ours:', error);
throw new Error(`Failed to mark host: ${error === null || error === void 0 ? void 0 : error.message}`);
}
});
}
/**
* Cambia el estado de un host (habilitado/deshabilitado)
*/
toggleHostState(domain_1, disable_1) {
return __awaiter(this, arguments, void 0, function* (domain, disable, ip = '127.0.0.1') {
try {
const content = yield fs.readFile(this.hostsFilePath, 'utf-8');
const lines = content.split('\n');
let modified = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Ignorar líneas vacías
if (line === '')
continue;
// Verificar si es un comentario de nuestra aplicación
if (line === APP_IDENTIFIER || line === DISABLED_IDENTIFIER)
continue;
// Verificar si es una línea comentada que necesitamos habilitar
const isCommentedLine = line.startsWith('#');
let actualLine = isCommentedLine ? line.substring(1).trim() : line;
const parts = actualLine.split(/\s+/);
if (parts.length >= 2 && parts[0] === ip && parts[1] === domain) {
// Verificar si la siguiente línea es nuestro identificador
const hasOurIdentifier = i < lines.length - 1 &&
(lines[i + 1].trim() === APP_IDENTIFIER || lines[i + 1].trim() === DISABLED_IDENTIFIER);
if (hasOurIdentifier) {
// Si queremos deshabilitar y ya está comentado, o habilitar y ya está sin comentar, no hacer nada
if ((disable && isCommentedLine) || (!disable && !isCommentedLine)) {
// Solo actualizar el identificador si es necesario
if ((disable && lines[i + 1].trim() !== DISABLED_IDENTIFIER) ||
(!disable && lines[i + 1].trim() !== APP_IDENTIFIER)) {
lines[i + 1] = disable ? DISABLED_IDENTIFIER : APP_IDENTIFIER;
modified = true;
}
}
else {
// Cambiar el estado
lines[i] = disable ? `# ${actualLine}` : actualLine;
lines[i + 1] = disable ? DISABLED_IDENTIFIER : APP_IDENTIFIER;
modified = true;
}
break;
}
}
}
if (modified) {
return yield this.writeHostsFile(lines.join('\n'));
}
return false;
}
catch (error) {
console.error('Error toggling host state:', error);
throw new Error(`Failed to toggle host state: ${error === null || error === void 0 ? void 0 : error.message}`);
}
});
}
/**
* Elimina un host que fue creado por nuestra aplicación
*/
removeHost(domain_1) {
return __awaiter(this, arguments, void 0, function* (domain, ip = '127.0.0.1') {
try {
const content = yield fs.readFile(this.hostsFilePath, 'utf-8');
const lines = content.split('\n');
let modified = false;
for (let i = 0; i < lines.length; i++) {
let line = lines[i].trim();
// Ignorar líneas vacías
if (line === '')
continue;
// Manejar líneas comentadas para buscar nuestros dominios deshabilitados
const isCommentedLine = line.startsWith('#');
if (isCommentedLine) {
// Si es una línea comentada, verificamos si es un dominio deshabilitado por nosotros
const actualLine = line.substring(1).trim();
const parts = actualLine.split(/\s+/);
if (parts.length >= 2 && parts[0] === ip && parts[1] === domain) {
// Verificar si la siguiente línea es nuestro identificador de deshabilitado
if (i < lines.length - 1 && lines[i + 1].trim() === DISABLED_IDENTIFIER) {
// Eliminar esta línea y la siguiente (el identificador)
lines.splice(i, 2);
modified = true;
break;
}
}
continue;
}
// Procesar líneas no comentadas
const parts = line.split(/\s+/);
if (parts.length >= 2 && parts[0] === ip && parts[1] === domain) {
// Verificar si la siguiente línea es nuestro identificador
if (i < lines.length - 1 &&
(lines[i + 1].trim() === APP_IDENTIFIER || lines[i + 1].trim() === DISABLED_IDENTIFIER)) {
// Eliminar esta línea y la siguiente (el identificador)
lines.splice(i, 2);
modified = true;
break;
}
}
}
if (modified) {
return yield this.writeHostsFile(lines.join('\n'));
}
return false;
}
catch (error) {
console.error('Error removing host:', error);
throw new Error(`Failed to remove host: ${error === null || error === void 0 ? void 0 : error.message}`);
}
});
}
/**
* Escribe contenido en el archivo hosts
* Asume que la aplicación ya tiene permisos elevados
*/
writeHostsFile(content) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield fs.writeFile(this.hostsFilePath, content, 'utf-8');
return true;
}
catch (error) {
console.error('Error writing hosts file:', error);
throw new Error(`Failed to write hosts file: ${error === null || error === void 0 ? void 0 : error.message}`);
}
});
}
/**
* Agrega contenido al final del archivo hosts
* Asume que la aplicación ya tiene permisos elevados
*/
appendToHostsFile(content) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield fs.appendFile(this.hostsFilePath, content, 'utf-8');
return true;
}
catch (error) {
console.error('Error appending to hosts file:', error);
throw new Error(`Failed to append to hosts file: ${error === null || error === void 0 ? void 0 : error.message}`);
}
});
}
}
exports.HostsManager = HostsManager;