initial commit

Signed-off-by: ale <ale@manalejandro.com>
Este commit está contenido en:
ale
2025-08-16 23:07:29 +02:00
padre 0dc3eb3f78
commit af164c1f8c
Se han modificado 18 ficheros con 1824 adiciones y 1788 borrados

2
.gitignore vendido
Ver fichero

@@ -39,3 +39,5 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
*.lock
*-lock.json

415
EXAMPLES.md Archivo normal
Ver fichero

@@ -0,0 +1,415 @@
# Ejemplos de Uso - API Ping Service
Este documento contiene ejemplos prácticos de cómo usar la API Ping Service en diferentes escenarios.
## 📡 Ejemplos de API
### 1. Ping Básico
```bash
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{
"target": "8.8.8.8",
"count": 4,
"timeout": 5000
}'
```
**Respuesta:**
```json
{
"success": true,
"target": "8.8.8.8",
"timestamp": "2025-08-16T21:00:00.000Z",
"results": [
{
"sequence": 1,
"time": 15.2,
"alive": true,
"host": "8.8.8.8"
}
],
"statistics": {
"packetsTransmitted": 4,
"packetsReceived": 4,
"packetLoss": "0.0",
"min": 14.1,
"max": 16.8,
"avg": "15.20"
}
}
```
### 2. Ping a Hostname
```bash
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{
"target": "google.com",
"count": 3,
"timeout": 3000
}'
```
### 3. Ping Rápido (1 ping)
```bash
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{
"target": "1.1.1.1",
"count": 1,
"timeout": 2000
}'
```
### 4. Verificar Estado del Servicio
```bash
curl -X GET http://localhost:3000/api/status
```
## 🚨 Ejemplos de Errores
### Rate Limit Excedido
```bash
# Después de 10 requests en 1 minuto
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{"target": "8.8.8.8"}'
```
**Respuesta (HTTP 429):**
```json
{
"error": "Rate limit exceeded",
"message": "Too many requests. Please try again later.",
"resetTime": 1692180660000,
"limit": 10,
"remaining": 0
}
```
### IP Privada (Bloqueada)
```bash
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{"target": "192.168.1.1"}'
```
**Respuesta (HTTP 400):**
```json
{
"error": "Invalid target",
"message": "Private, loopback, or reserved IP addresses are not allowed"
}
```
### Target Inválido
```bash
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{"target": "invalid..hostname"}'
```
**Respuesta (HTTP 400):**
```json
{
"error": "Invalid target",
"message": "Invalid IP address or hostname format"
}
```
## 💻 Ejemplos en JavaScript
### 1. Función de Ping Simple
```javascript
async function pingHost(target, count = 4) {
try {
const response = await fetch('/api/ping', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
target,
count,
timeout: 5000
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}
const result = await response.json();
console.log(`Ping to ${target}:`);
console.log(`Average: ${result.statistics.avg}ms`);
console.log(`Packet Loss: ${result.statistics.packetLoss}%`);
return result;
} catch (error) {
console.error('Ping failed:', error.message);
throw error;
}
}
// Uso
pingHost('8.8.8.8', 3);
```
### 2. Monitor de Múltiples Hosts
```javascript
async function monitorHosts(hosts) {
const results = [];
for (const host of hosts) {
try {
const result = await pingHost(host, 2);
results.push({
host,
success: true,
averageTime: result.statistics.avg,
packetLoss: result.statistics.packetLoss
});
} catch (error) {
results.push({
host,
success: false,
error: error.message
});
}
// Esperar 2 segundos entre hosts para no saturar
await new Promise(resolve => setTimeout(resolve, 2000));
}
return results;
}
// Uso
const hosts = ['8.8.8.8', '1.1.1.1', 'google.com', 'github.com'];
monitorHosts(hosts).then(console.log);
```
### 3. Verificador de Rate Limit
```javascript
async function checkRateLimit() {
try {
const response = await fetch('/api/status');
const data = await response.json();
const rateLimit = data.clientInfo.rateLimit;
console.log(`Rate Limit: ${rateLimit.remaining}/${rateLimit.limit} remaining`);
if (rateLimit.remaining < 3) {
console.warn('⚠️ Approaching rate limit!');
}
return rateLimit;
} catch (error) {
console.error('Failed to check rate limit:', error);
return null;
}
}
```
### 4. Ping con Reintentos
```javascript
async function pingWithRetry(target, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
console.log(`Attempt ${attempt}/${maxRetries} for ${target}`);
const result = await pingHost(target, 1);
console.log(`✅ Success on attempt ${attempt}`);
return result;
} catch (error) {
console.log(`❌ Attempt ${attempt} failed: ${error.message}`);
if (attempt === maxRetries) {
throw new Error(`Failed after ${maxRetries} attempts: ${error.message}`);
}
// Esperar antes del siguiente intento
const delay = attempt * 1000; // 1s, 2s, 3s...
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
```
## 🐍 Ejemplos en Python
### 1. Cliente Python Simple
```python
import requests
import json
import time
class PingClient:
def __init__(self, base_url="http://localhost:3000"):
self.base_url = base_url
def ping(self, target, count=4, timeout=5000):
"""Realiza un ping al target especificado"""
url = f"{self.base_url}/api/ping"
data = {
"target": target,
"count": count,
"timeout": timeout
}
try:
response = requests.post(url, json=data)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return None
def get_status(self):
"""Obtiene el estado del servicio"""
url = f"{self.base_url}/api/status"
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return None
# Uso
client = PingClient()
# Ping simple
result = client.ping("8.8.8.8", count=3)
if result:
print(f"Average: {result['statistics']['avg']}ms")
# Verificar estado
status = client.get_status()
if status:
print(f"Service: {status['service']}")
print(f"Rate limit: {status['clientInfo']['rateLimit']['remaining']}/10")
```
### 2. Monitor Continuo
```python
import time
import datetime
def monitor_host(client, target, interval=60, duration=3600):
"""Monitorea un host durante un período específico"""
start_time = time.time()
end_time = start_time + duration
print(f"Monitoring {target} for {duration/60} minutes...")
while time.time() < end_time:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
result = client.ping(target, count=1)
if result and result.get('success'):
avg_time = result['statistics']['avg']
packet_loss = result['statistics']['packetLoss']
print(f"[{timestamp}] {target}: {avg_time}ms (loss: {packet_loss}%)")
else:
print(f"[{timestamp}] {target}: FAILED")
time.sleep(interval)
# Uso
client = PingClient()
monitor_host(client, "8.8.8.8", interval=30, duration=1800) # 30 min
```
## 🔧 Headers de Rate Limiting
El servicio incluye headers HTTP para monitorear el rate limiting:
```bash
curl -I -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{"target": "8.8.8.8"}'
```
**Headers de respuesta:**
```
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 9
X-RateLimit-Reset: 1692180660000
```
## 🚀 Casos de Uso Avanzados
### Dashboard de Monitoreo
```javascript
class NetworkDashboard {
constructor() {
this.hosts = ['8.8.8.8', '1.1.1.1', 'google.com'];
this.results = new Map();
}
async updateStatus() {
for (const host of this.hosts) {
try {
const result = await pingHost(host, 1);
this.results.set(host, {
status: 'up',
latency: result.statistics.avg,
lastCheck: new Date()
});
} catch (error) {
this.results.set(host, {
status: 'down',
error: error.message,
lastCheck: new Date()
});
}
}
this.displayResults();
}
displayResults() {
console.clear();
console.log('🌐 Network Status Dashboard');
console.log('=' .repeat(40));
this.results.forEach((result, host) => {
const icon = result.status === 'up' ? '✅' : '❌';
const info = result.status === 'up'
? `${result.latency}ms`
: result.error;
console.log(`${icon} ${host.padEnd(15)} ${info}`);
});
}
start(interval = 30000) {
this.updateStatus();
setInterval(() => this.updateStatus(), interval);
}
}
// Uso
const dashboard = new NetworkDashboard();
dashboard.start(30000); // Actualizar cada 30 segundos
```
Estos ejemplos muestran cómo integrar el servicio de ping en diferentes aplicaciones y escenarios de uso real.

Ver fichero

@@ -1,36 +1,61 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
# API Ping Service
## Getting Started
Un servicio moderno de ping construido con Next.js 15 que permite realizar pruebas de conectividad de red de forma segura y controlada.
First, run the development server:
## 🚀 Características
- **Rate Limiting**: Máximo 10 peticiones por minuto por IP para prevenir abuso
- **Validación de seguridad**: Bloquea IPs privadas, localhost y rangos reservados
- **Interfaz moderna**: UI responsiva con Tailwind CSS
- **Tiempo real**: Resultados en tiempo real con indicadores de progreso
- **Estadísticas completas**: Métricas detalladas de latencia, pérdida de paquetes, etc.
- **API RESTful**: Endpoints bien documentados para integración
## 🔧 Instalación
```bash
# Instalar dependencias
npm install
# Ejecutar en modo desarrollo
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
# Ejecutar en producción
npm run build
npm start
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
## 📡 API Endpoints
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
### POST /api/ping
Realiza una prueba de ping al destino especificado.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
**Request Body:**
```json
{
"target": "8.8.8.8", // IP o hostname (requerido)
"count": 4, // Número de pings (1-10, default: 4)
"timeout": 5000 // Timeout en ms (1000-10000, default: 5000)
}
```
## Learn More
### GET /api/status
Obtiene información del estado del servicio y estadísticas del cliente.
To learn more about Next.js, take a look at the following resources:
## 🛡️ Seguridad
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
### Rate Limiting
- **Límite**: 10 peticiones por minuto por IP
- **Ventana deslizante**: Se renueva automáticamente
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
### Validaciones
- ✅ IPs públicas válidas (IPv4/IPv6)
- ✅ Hostnames válidos según RFC 1123
- ❌ IPs privadas, localhost y rangos reservados
## Deploy on Vercel
## 🎨 Interfaz de Usuario
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
- **Responsive**: Optimizada para móviles y escritorio
- **Dark Mode**: Soporte completo para tema oscuro
- **Tiempo Real**: Indicadores de progreso durante las pruebas
- **Quick Select**: Botones rápidos para destinos comunes

1670
package-lock.json generado

La diferencia del archivo ha sido suprimido porque es demasiado grande Cargar Diff

Ver fichero

@@ -9,9 +9,15 @@
"lint": "next lint"
},
"dependencies": {
"@vercel/kv": "^3.0.0",
"ip-regex": "^5.0.0",
"next": "15.4.6",
"node-cache": "^5.1.2",
"ping": "^0.4.4",
"react": "19.1.0",
"react-dom": "19.1.0",
"next": "15.4.6"
"redis-memory-server": "^0.12.1",
"validator": "^13.15.15"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",

166
src/app/api/ping/route.js Archivo normal
Ver fichero

@@ -0,0 +1,166 @@
import ping from 'ping';
import { NextResponse } from 'next/server';
import { RateLimiter } from '../../../lib/rate-limiter';
import { validateIP } from '../../../lib/validators';
import { PING_CONFIG } from '../../../lib/config.js';
// Crear instancia del rate limiter
const rateLimiter = new RateLimiter();
export async function POST(request) {
try {
// Obtener IP del cliente para rate limiting
const forwarded = request.headers.get('x-forwarded-for');
const clientIP = forwarded
? forwarded.split(',')[0].trim()
: request.headers.get('x-real-ip') || 'unknown';
// Verificar rate limit
const rateLimitResult = await rateLimiter.checkLimit(clientIP);
if (!rateLimitResult.allowed) {
return NextResponse.json({
error: 'Rate limit exceeded',
message: 'Too many requests. Please try again later.',
resetTime: rateLimitResult.resetTime,
limit: rateLimitResult.limit,
remaining: rateLimitResult.remaining
}, {
status: 429,
headers: {
'X-RateLimit-Limit': rateLimitResult.limit.toString(),
'X-RateLimit-Remaining': rateLimitResult.remaining.toString(),
'X-RateLimit-Reset': rateLimitResult.resetTime.toString()
}
});
}
// Parsear el body de la request
const body = await request.json();
const { target, count = 4, timeout = 5000 } = body;
// Validar parámetros
if (!target) {
return NextResponse.json({
error: 'Missing target',
message: 'Target IP or hostname is required'
}, { status: 400 });
}
// Validar IP/hostname
const validationResult = validateIP(target);
if (!validationResult.valid) {
return NextResponse.json({
error: 'Invalid target',
message: validationResult.message
}, { status: 400 });
}
// Validar count (usar configuración)
const pingCount = Math.min(
Math.max(parseInt(count) || PING_CONFIG.PING_LIMITS.DEFAULT_COUNT, PING_CONFIG.PING_LIMITS.MIN_COUNT),
PING_CONFIG.PING_LIMITS.MAX_COUNT
);
// Validar timeout (usar configuración)
const pingTimeout = Math.min(
Math.max(parseInt(timeout) || PING_CONFIG.PING_LIMITS.DEFAULT_TIMEOUT, PING_CONFIG.PING_LIMITS.MIN_TIMEOUT),
PING_CONFIG.PING_LIMITS.MAX_TIMEOUT
);
// Realizar el ping
const results = [];
const startTime = Date.now();
for (let i = 0; i < pingCount; i++) {
try {
const result = await ping.promise.probe(target, {
timeout: pingTimeout / 1000, // ping library expects seconds
min_reply: 1,
deadline: 30
});
results.push({
sequence: i + 1,
time: result.time === 'unknown' ? null : parseFloat(result.time),
alive: result.alive,
host: result.host,
numeric_host: result.numeric_host,
output: result.output
});
// Esperar entre pings (usar configuración)
if (i < pingCount - 1) {
await new Promise(resolve => setTimeout(resolve, PING_CONFIG.NETWORK.PING_INTERVAL_MS));
}
} catch (error) {
results.push({
sequence: i + 1,
time: null,
alive: false,
host: target,
error: error.message
});
}
}
const endTime = Date.now();
const totalTime = endTime - startTime;
// Calcular estadísticas
const successfulPings = results.filter(r => r.alive && r.time !== null);
const times = successfulPings.map(r => r.time);
const stats = {
packetsTransmitted: pingCount,
packetsReceived: successfulPings.length,
packetLoss: ((pingCount - successfulPings.length) / pingCount * 100).toFixed(1),
totalTime: totalTime,
min: times.length > 0 ? Math.min(...times) : null,
max: times.length > 0 ? Math.max(...times) : null,
avg: times.length > 0 ? (times.reduce((a, b) => a + b, 0) / times.length).toFixed(2) : null
};
return NextResponse.json({
success: true,
target: target,
timestamp: new Date().toISOString(),
results: results,
statistics: stats,
rateLimit: {
limit: rateLimitResult.limit,
remaining: rateLimitResult.remaining - 1,
resetTime: rateLimitResult.resetTime
}
}, {
headers: {
'X-RateLimit-Limit': rateLimitResult.limit.toString(),
'X-RateLimit-Remaining': (rateLimitResult.remaining - 1).toString(),
'X-RateLimit-Reset': rateLimitResult.resetTime.toString()
}
});
} catch (error) {
console.error('Ping API error:', error);
return NextResponse.json({
error: 'Internal server error',
message: 'An error occurred while processing the ping request'
}, { status: 500 });
}
}
export async function GET() {
return NextResponse.json({
message: 'Ping API Service',
description: 'Send a POST request with a target IP or hostname to perform a ping test',
usage: {
method: 'POST',
body: {
target: 'IP address or hostname (required)',
count: 'Number of pings (1-10, default: 4)',
timeout: 'Timeout in milliseconds (1000-10000, default: 5000)'
}
},
rateLimit: 'Maximum 10 requests per minute per IP address'
});
}

69
src/app/api/status/route.js Archivo normal
Ver fichero

@@ -0,0 +1,69 @@
import { NextResponse } from 'next/server';
import { RateLimiter } from '../../../lib/rate-limiter';
// Crear instancia del rate limiter
const rateLimiter = new RateLimiter();
export async function GET(request) {
try {
// Obtener IP del cliente
const forwarded = request.headers.get('x-forwarded-for');
const clientIP = forwarded
? forwarded.split(',')[0].trim()
: request.headers.get('x-real-ip') || 'unknown';
// Obtener estadísticas del rate limiter para este cliente
const rateLimitStats = rateLimiter.getStats(clientIP);
return NextResponse.json({
service: 'API Ping Service',
version: '1.0.0',
status: 'operational',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
clientInfo: {
ip: clientIP,
rateLimit: rateLimitStats
},
features: {
maxPingsPerRequest: 10,
maxTimeout: 10000,
minTimeout: 1000,
supportedProtocols: ['ICMP'],
restrictions: [
'No private IP addresses',
'No localhost addresses',
'No reserved IP ranges',
'Rate limited to 10 requests per minute'
]
},
endpoints: {
ping: {
path: '/api/ping',
method: 'POST',
description: 'Perform ping test to specified target',
parameters: {
target: 'IP address or hostname (required)',
count: 'Number of pings (1-10, default: 4)',
timeout: 'Timeout in milliseconds (1000-10000, default: 5000)'
}
},
status: {
path: '/api/status',
method: 'GET',
description: 'Get service status and client information'
}
}
});
} catch (error) {
console.error('Status API error:', error);
return NextResponse.json({
service: 'API Ping Service',
status: 'error',
timestamp: new Date().toISOString(),
error: 'Internal server error'
}, { status: 500 });
}
}

Ver fichero

@@ -0,0 +1,45 @@
'use client';
import { useState } from 'react';
export default function CopyButton({ text, className = '' }) {
const [copied, setCopied] = useState(false);
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
};
return (
<button
onClick={handleCopy}
className={`inline-flex items-center px-2 py-1 text-xs font-medium rounded transition-colors ${
copied
? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'
} ${className}`}
title={copied ? 'Copied!' : 'Copy to clipboard'}
>
{copied ? (
<>
<svg className="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
Copied!
</>
) : (
<>
<svg className="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
Copy
</>
)}
</button>
);
}

137
src/app/components/PingForm.js Archivo normal
Ver fichero

@@ -0,0 +1,137 @@
'use client';
import { useState } from 'react';
export default function PingForm({ onSubmit, isLoading, onCancel }) {
const [target, setTarget] = useState('');
const [count, setCount] = useState(4);
const [timeout, setTimeout] = useState(5000);
const handleSubmit = (e) => {
e.preventDefault();
if (!target.trim()) return;
onSubmit({
target: target.trim(),
count: parseInt(count),
timeout: parseInt(timeout),
});
};
const commonTargets = [
{ name: 'Google DNS', value: '8.8.8.8' },
{ name: 'Cloudflare DNS', value: '1.1.1.1' },
{ name: 'Google.com', value: 'google.com' },
{ name: 'GitHub.com', value: 'github.com' },
];
return (
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label htmlFor="target" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Target IP Address or Hostname
</label>
<input
type="text"
id="target"
value={target}
onChange={(e) => setTarget(e.target.value)}
placeholder="e.g., 8.8.8.8 or google.com"
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
required
disabled={isLoading}
/>
{/* Quick Select Buttons */}
<div className="mt-3 flex flex-wrap gap-2">
<span className="text-xs font-medium text-gray-600 dark:text-gray-400 mr-2">Quick select:</span>
{commonTargets.map((item) => (
<button
key={item.value}
type="button"
onClick={() => setTarget(item.value)}
className="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors"
disabled={isLoading}
>
{item.name}
</button>
))}
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label htmlFor="count" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Number of Pings
</label>
<select
id="count"
value={count}
onChange={(e) => setCount(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
disabled={isLoading}
>
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(num => (
<option key={num} value={num}>{num}</option>
))}
</select>
</div>
<div>
<label htmlFor="timeout" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Timeout (seconds)
</label>
<select
id="timeout"
value={timeout}
onChange={(e) => setTimeout(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
disabled={isLoading}
>
<option value={1000}>1</option>
<option value={2000}>2</option>
<option value={3000}>3</option>
<option value={5000}>5</option>
<option value={7000}>7</option>
<option value={10000}>10</option>
</select>
</div>
</div>
<div className="flex space-x-3">
<button
type="submit"
disabled={isLoading || !target.trim()}
className="flex-1 flex justify-center items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-medium rounded-lg shadow transition-colors"
>
{isLoading ? (
<>
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
Pinging...
</>
) : (
<>
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
Start Ping Test
</>
)}
</button>
{isLoading && onCancel && (
<button
type="button"
onClick={onCancel}
className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg shadow transition-colors"
>
Cancel
</button>
)}
</div>
</form>
);
}

Ver fichero

@@ -0,0 +1,111 @@
'use client';
import { useEffect } from 'react';
import { usePingService } from '../../hooks/usePingService';
import PingForm from './PingForm';
import PingResults from './PingResults';
import RateLimitInfo from './RateLimitInfo';
export default function PingInterface() {
const {
isLoading,
results,
error,
rateLimitInfo,
executePing,
cancelPing,
clearResults,
fetchStatus
} = usePingService();
// Cargar información inicial del estado al montar el componente
useEffect(() => {
fetchStatus();
}, [fetchStatus]);
return (
<div className="space-y-6">
{/* Rate Limit Information */}
{rateLimitInfo && <RateLimitInfo rateLimitInfo={rateLimitInfo} />}
{/* Ping Form */}
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
<PingForm
onSubmit={executePing}
isLoading={isLoading}
onCancel={cancelPing}
/>
</div>
{/* Error Display */}
{error && (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<div className="flex items-center justify-between">
<div className="flex items-center">
<div className="flex-shrink-0">
<svg className="w-5 h-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
</svg>
</div>
<div className="ml-3">
<h3 className="text-sm font-medium text-red-800 dark:text-red-200">
Error
</h3>
<div className="mt-1 text-sm text-red-700 dark:text-red-300">
{error}
</div>
</div>
</div>
<button
onClick={clearResults}
className="text-red-400 hover:text-red-600 transition-colors"
title="Dismiss error"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
)}
{/* Results Display */}
{results && (
<div className="space-y-4">
<PingResults results={results} />
<div className="flex justify-center">
<button
onClick={clearResults}
className="px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg transition-colors"
>
Clear Results
</button>
</div>
</div>
)}
{/* Usage Information */}
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<div className="flex items-start">
<div className="flex-shrink-0">
<svg className="w-5 h-5 text-blue-400 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
</svg>
</div>
<div className="ml-3 text-sm">
<h3 className="font-medium text-blue-800 dark:text-blue-200 mb-2">
Usage Guidelines
</h3>
<ul className="text-blue-700 dark:text-blue-300 space-y-1">
<li> Maximum 10 requests per minute per IP address</li>
<li> Maximum 10 pings per request</li>
<li> Timeout range: 1-10 seconds</li>
<li> Private IPs and localhost are blocked for security</li>
<li> Only public IP addresses and valid hostnames are allowed</li>
</ul>
</div>
</div>
</div>
</div>
);
}

Ver fichero

@@ -0,0 +1,176 @@
'use client';
import CopyButton from './CopyButton';
export default function PingResults({ results }) {
const { target, timestamp, results: pingResults, statistics } = results;
const formatTime = (time) => {
if (time === null || time === undefined) return 'N/A';
return `${time}ms`;
};
const formatTimestamp = (isoString) => {
return new Date(isoString).toLocaleString();
};
const getStatusColor = (alive) => {
return alive ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400';
};
const getStatusIcon = (alive) => {
if (alive) {
return (
<svg className="w-4 h-4 text-green-500" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
</svg>
);
} else {
return (
<svg className="w-4 h-4 text-red-500" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
</svg>
);
}
};
return (
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg overflow-hidden">
{/* Header */}
<div className="bg-gray-50 dark:bg-gray-700 px-6 py-4 border-b border-gray-200 dark:border-gray-600">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
Ping Results for {target}
</h2>
<p className="text-sm text-gray-600 dark:text-gray-400">
Test completed at {formatTimestamp(timestamp)}
</p>
</div>
{/* Statistics Summary */}
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-700/50">
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="text-center">
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{statistics.packetsTransmitted}
</div>
<div className="text-sm text-gray-600 dark:text-gray-400">Sent</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-green-600 dark:text-green-400">
{statistics.packetsReceived}
</div>
<div className="text-sm text-gray-600 dark:text-gray-400">Received</div>
</div>
<div className="text-center">
<div className={`text-2xl font-bold ${parseFloat(statistics.packetLoss) > 0 ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400'}`}>
{statistics.packetLoss}%
</div>
<div className="text-sm text-gray-600 dark:text-gray-400">Loss</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-blue-600 dark:text-blue-400">
{statistics.avg ? `${statistics.avg}ms` : 'N/A'}
</div>
<div className="text-sm text-gray-600 dark:text-gray-400">Avg Time</div>
</div>
</div>
{statistics.min !== null && statistics.max !== null && (
<div className="mt-4 text-center text-sm text-gray-600 dark:text-gray-400">
Min: {statistics.min}ms Max: {statistics.max}ms Total Time: {statistics.totalTime}ms
</div>
)}
</div>
{/* Individual Ping Results */}
<div className="px-6 py-4">
<h3 className="text-md font-medium text-gray-900 dark:text-white mb-4">
Individual Ping Results
</h3>
<div className="space-y-2">
{pingResults.map((result) => (
<div
key={result.sequence}
className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"
>
<div className="flex items-center space-x-3">
{getStatusIcon(result.alive)}
<span className="text-sm font-medium text-gray-900 dark:text-white">
Ping #{result.sequence}
</span>
{result.host && result.host !== target && (
<span className="text-xs text-gray-500 dark:text-gray-400">
({result.host})
</span>
)}
</div>
<div className="flex items-center space-x-4">
<span className={`text-sm font-medium ${getStatusColor(result.alive)}`}>
{result.alive ? 'Success' : 'Failed'}
</span>
<span className="text-sm text-gray-600 dark:text-gray-400 min-w-[60px] text-right">
{formatTime(result.time)}
</span>
</div>
</div>
))}
</div>
</div>
{/* Raw Output (if available) */}
{pingResults.some(r => r.output) && (
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-700/50 border-t border-gray-200 dark:border-gray-600">
<details className="group">
<summary className="cursor-pointer text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white flex items-center justify-between">
<div className="flex items-center">
<svg className="w-4 h-4 mr-2 transform transition-transform group-open:rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
Show Raw Terminal Output
<span className="ml-2 px-2 py-1 text-xs bg-gray-200 dark:bg-gray-600 rounded">
{pingResults.filter(r => r.output).length} ping{pingResults.filter(r => r.output).length !== 1 ? 's' : ''}
</span>
</div>
<CopyButton
text={pingResults.filter(r => r.output).map(r => `Ping #${r.sequence}:\n${r.output}`).join('\n\n')}
className="ml-2"
/>
</summary>
<div className="mt-3 space-y-3">
{pingResults
.filter(r => r.output)
.map((r, index) => (
<div key={index} className="bg-gray-900 dark:bg-gray-800 rounded-lg border border-gray-700 overflow-hidden">
<div className="bg-gray-800 dark:bg-gray-700 px-3 py-2 border-b border-gray-700 flex items-center justify-between">
<div className="flex items-center space-x-2">
<div className="flex space-x-1">
<div className="w-3 h-3 bg-red-500 rounded-full"></div>
<div className="w-3 h-3 bg-yellow-500 rounded-full"></div>
<div className="w-3 h-3 bg-green-500 rounded-full"></div>
</div>
<span className="text-sm font-medium text-white">
Ping #{r.sequence} - {r.alive ? '✅ Success' : '❌ Failed'}
</span>
</div>
<div className="flex items-center space-x-2">
<span className="text-xs text-gray-400">
{r.time ? `${r.time}ms` : 'No response'}
</span>
<CopyButton text={r.output} />
</div>
</div>
<div className="p-4">
<pre className="text-xs text-green-400 font-mono whitespace-pre-wrap break-words leading-relaxed">
{r.output}
</pre>
</div>
</div>
))}
</div>
</details>
</div>
)}
</div>
);
}

Ver fichero

@@ -0,0 +1,116 @@
'use client';
export default function RateLimitInfo({ rateLimitInfo }) {
const { limit, remaining, resetTime } = rateLimitInfo;
const formatResetTime = (timestamp) => {
const resetDate = new Date(timestamp);
const now = new Date();
const diffMs = resetDate - now;
if (diffMs <= 0) {
return 'Now';
}
const diffSeconds = Math.ceil(diffMs / 1000);
if (diffSeconds < 60) {
return `${diffSeconds}s`;
}
const diffMinutes = Math.ceil(diffSeconds / 60);
return `${diffMinutes}m`;
};
const getStatusColor = () => {
const percentage = (remaining / limit) * 100;
if (percentage > 50) {
return 'bg-green-500';
} else if (percentage > 20) {
return 'bg-yellow-500';
} else {
return 'bg-red-500';
}
};
const getTextColor = () => {
const percentage = (remaining / limit) * 100;
if (percentage > 50) {
return 'text-green-700 dark:text-green-300';
} else if (percentage > 20) {
return 'text-yellow-700 dark:text-yellow-300';
} else {
return 'text-red-700 dark:text-red-300';
}
};
const getBorderColor = () => {
const percentage = (remaining / limit) * 100;
if (percentage > 50) {
return 'border-green-200 dark:border-green-800';
} else if (percentage > 20) {
return 'border-yellow-200 dark:border-yellow-800';
} else {
return 'border-red-200 dark:border-red-800';
}
};
const getBgColor = () => {
const percentage = (remaining / limit) * 100;
if (percentage > 50) {
return 'bg-green-50 dark:bg-green-900/20';
} else if (percentage > 20) {
return 'bg-yellow-50 dark:bg-yellow-900/20';
} else {
return 'bg-red-50 dark:bg-red-900/20';
}
};
return (
<div className={`${getBgColor()} border ${getBorderColor()} rounded-lg p-4`}>
<div className="flex items-center justify-between mb-3">
<h3 className={`text-sm font-medium ${getTextColor()}`}>
Rate Limit Status
</h3>
<span className="text-xs text-gray-500 dark:text-gray-400">
Resets in {formatResetTime(resetTime)}
</span>
</div>
<div className="flex items-center space-x-4">
<div className="flex-1">
<div className="flex justify-between text-xs text-gray-600 dark:text-gray-400 mb-1">
<span>Requests remaining</span>
<span>{remaining} / {limit}</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
<div
className={`h-2 rounded-full transition-all duration-300 ${getStatusColor()}`}
style={{ width: `${(remaining / limit) * 100}%` }}
/>
</div>
</div>
<div className="text-right">
<div className={`text-lg font-bold ${getTextColor()}`}>
{remaining}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400">
left
</div>
</div>
</div>
{remaining <= 2 && (
<div className="mt-3 text-xs text-red-600 dark:text-red-400">
You're approaching the rate limit. Please wait before making more requests.
</div>
)}
</div>
);
}

Ver fichero

@@ -1,103 +1,27 @@
import Image from "next/image";
import PingInterface from './components/PingInterface';
export default function Home() {
return (
<div className="font-sans grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20">
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="font-mono list-inside list-decimal text-sm/6 text-center sm:text-left">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] font-mono font-semibold px-1 py-0.5 rounded">
src/app/page.js
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-gray-900 dark:to-gray-800">
<div className="container mx-auto px-4 py-8">
<header className="text-center mb-8">
<h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
🏓 API Ping Service
</h1>
<p className="text-lg text-gray-600 dark:text-gray-300 max-w-2xl mx-auto">
Test network connectivity to any IP address or hostname with our secure ping service.
Rate limited for fair usage and designed with modern security practices.
</p>
</header>
<main className="max-w-4xl mx-auto">
<PingInterface />
</main>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
<footer className="text-center mt-12 text-sm text-gray-500 dark:text-gray-400">
<p>Built with Next.js 15 Rate limited to 10 requests per minute</p>
</footer>
</div>
</div>
);
}

108
src/hooks/usePingService.js Archivo normal
Ver fichero

@@ -0,0 +1,108 @@
import { useState, useCallback, useRef } from 'react';
export function usePingService() {
const [isLoading, setIsLoading] = useState(false);
const [results, setResults] = useState(null);
const [error, setError] = useState(null);
const [rateLimitInfo, setRateLimitInfo] = useState(null);
const abortControllerRef = useRef(null);
const executePing = useCallback(async (formData) => {
// Cancelar request anterior si existe
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
// Crear nuevo AbortController
abortControllerRef.current = new AbortController();
setIsLoading(true);
setError(null);
setResults(null);
try {
const response = await fetch('/api/ping', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
signal: abortControllerRef.current.signal,
});
const data = await response.json();
// Actualizar información de rate limit desde headers
if (response.headers.get('X-RateLimit-Limit')) {
setRateLimitInfo({
limit: parseInt(response.headers.get('X-RateLimit-Limit')),
remaining: parseInt(response.headers.get('X-RateLimit-Remaining')),
resetTime: parseInt(response.headers.get('X-RateLimit-Reset')),
});
}
if (!response.ok) {
throw new Error(data.message || `HTTP ${response.status}: ${response.statusText}`);
}
setResults(data);
// Actualizar rate limit info desde la respuesta si está disponible
if (data.rateLimit) {
setRateLimitInfo(data.rateLimit);
}
} catch (err) {
// No mostrar error si fue cancelado
if (err.name !== 'AbortError') {
setError(err.message);
}
} finally {
setIsLoading(false);
abortControllerRef.current = null;
}
}, []);
const cancelPing = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
setIsLoading(false);
}
}, []);
const clearResults = useCallback(() => {
setResults(null);
setError(null);
}, []);
const fetchStatus = useCallback(async () => {
try {
const response = await fetch('/api/status');
const data = await response.json();
if (data.clientInfo?.rateLimit) {
setRateLimitInfo(data.clientInfo.rateLimit);
}
return data;
} catch (err) {
console.error('Failed to fetch status:', err);
return null;
}
}, []);
return {
// Estado
isLoading,
results,
error,
rateLimitInfo,
// Acciones
executePing,
cancelPing,
clearResults,
fetchStatus,
};
}

119
src/lib/config.js Archivo normal
Ver fichero

@@ -0,0 +1,119 @@
// Configuración del servicio de ping
export const PING_CONFIG = {
// Rate limiting
RATE_LIMIT: {
MAX_REQUESTS: parseInt(process.env.RATE_LIMIT_MAX) || 10,
WINDOW_MS: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 60 * 1000, // 1 minuto
},
// Límites de ping
PING_LIMITS: {
MAX_COUNT: parseInt(process.env.PING_MAX_COUNT) || 10,
MIN_COUNT: 1,
MAX_TIMEOUT: parseInt(process.env.PING_MAX_TIMEOUT) || 10000, // 10 segundos
MIN_TIMEOUT: 1000, // 1 segundo
DEFAULT_COUNT: 4,
DEFAULT_TIMEOUT: 5000, // 5 segundos
},
// Configuración de seguridad
SECURITY: {
BLOCK_PRIVATE_IPS: true,
BLOCK_LOCALHOST: true,
BLOCK_RESERVED_RANGES: true,
ALLOWED_PROTOCOLS: ['ICMP'],
},
// Configuración de red
NETWORK: {
MAX_CONCURRENT_PINGS: 5,
PING_INTERVAL_MS: 1000, // Intervalo entre pings individuales
MAX_HOSTNAME_LENGTH: 253,
MAX_LABEL_LENGTH: 63,
},
// Headers de respuesta
HEADERS: {
INCLUDE_RATE_LIMIT_HEADERS: true,
INCLUDE_SECURITY_HEADERS: true,
CORS_ENABLED: true,
},
// Logging y debugging
DEBUG: {
LOG_REQUESTS: process.env.NODE_ENV === 'development',
LOG_RATE_LIMITS: process.env.NODE_ENV === 'development',
INCLUDE_RAW_OUTPUT: true,
}
};
// Validador de configuración
export function validateConfig() {
const errors = [];
if (PING_CONFIG.RATE_LIMIT.MAX_REQUESTS <= 0) {
errors.push('MAX_REQUESTS must be greater than 0');
}
if (PING_CONFIG.PING_LIMITS.MAX_COUNT > 50) {
errors.push('MAX_COUNT should not exceed 50 for performance reasons');
}
if (PING_CONFIG.PING_LIMITS.MAX_TIMEOUT > 30000) {
errors.push('MAX_TIMEOUT should not exceed 30 seconds');
}
if (errors.length > 0) {
throw new Error(`Configuration validation failed: ${errors.join(', ')}`);
}
return true;
}
// Configuración específica por entorno
export function getEnvironmentConfig() {
const env = process.env.NODE_ENV || 'development';
const envConfigs = {
development: {
RATE_LIMIT: {
MAX_REQUESTS: 20, // Más permisivo en desarrollo
WINDOW_MS: 60 * 1000,
},
DEBUG: {
LOG_REQUESTS: true,
LOG_RATE_LIMITS: true,
INCLUDE_RAW_OUTPUT: true,
}
},
production: {
RATE_LIMIT: {
MAX_REQUESTS: 10, // Más restrictivo en producción
WINDOW_MS: 60 * 1000,
},
DEBUG: {
LOG_REQUESTS: false,
LOG_RATE_LIMITS: false,
INCLUDE_RAW_OUTPUT: false,
}
},
test: {
RATE_LIMIT: {
MAX_REQUESTS: 100, // Sin límites en tests
WINDOW_MS: 60 * 1000,
},
DEBUG: {
LOG_REQUESTS: false,
LOG_RATE_LIMITS: false,
INCLUDE_RAW_OUTPUT: false,
}
}
};
return {
...PING_CONFIG,
...envConfigs[env]
};
}

100
src/lib/rate-limiter.js Archivo normal
Ver fichero

@@ -0,0 +1,100 @@
import NodeCache from 'node-cache';
import { PING_CONFIG } from './config.js';
export class RateLimiter {
constructor(options = {}) {
// Usar configuración por defecto o personalizada
this.limit = options.limit || PING_CONFIG.RATE_LIMIT.MAX_REQUESTS;
this.windowMs = options.windowMs || PING_CONFIG.RATE_LIMIT.WINDOW_MS;
// Cache con TTL automático
this.cache = new NodeCache({
stdTTL: this.windowMs / 1000,
checkperiod: 60 // revisar cada 60 segundos
});
}
async checkLimit(identifier) {
const key = `rate_limit:${identifier}`;
const now = Date.now();
const windowStart = now - this.windowMs;
// Obtener datos actuales del cache
let data = this.cache.get(key) || {
requests: [],
resetTime: now + this.windowMs
};
// Filtrar requests dentro de la ventana de tiempo
data.requests = data.requests.filter(timestamp => timestamp > windowStart);
// Verificar si se excede el límite
const requestCount = data.requests.length;
const allowed = requestCount < this.limit;
if (allowed) {
// Agregar la nueva request
data.requests.push(now);
// Si es la primera request en esta ventana, actualizar resetTime
if (data.requests.length === 1) {
data.resetTime = now + this.windowMs;
}
// Guardar en cache
this.cache.set(key, data, this.windowMs / 1000);
}
return {
allowed,
limit: this.limit,
remaining: Math.max(0, this.limit - requestCount - (allowed ? 1 : 0)),
resetTime: data.resetTime,
requestCount: requestCount + (allowed ? 1 : 0)
};
}
// Método para obtener estadísticas de un cliente
getStats(identifier) {
const key = `rate_limit:${identifier}`;
const data = this.cache.get(key);
if (!data) {
return {
limit: this.limit,
remaining: this.limit,
requestCount: 0,
resetTime: Date.now() + this.windowMs
};
}
const now = Date.now();
const windowStart = now - this.windowMs;
const validRequests = data.requests.filter(timestamp => timestamp > windowStart);
return {
limit: this.limit,
remaining: Math.max(0, this.limit - validRequests.length),
requestCount: validRequests.length,
resetTime: data.resetTime
};
}
// Método para limpiar el cache manualmente
clear() {
this.cache.flushAll();
}
// Método para obtener todas las estadísticas (útil para debugging)
getAllStats() {
const keys = this.cache.keys();
const stats = {};
keys.forEach(key => {
const identifier = key.replace('rate_limit:', '');
stats[identifier] = this.getStats(identifier);
});
return stats;
}
}

149
src/lib/validators.js Archivo normal
Ver fichero

@@ -0,0 +1,149 @@
import ipRegex from 'ip-regex';
export function validateIP(target) {
if (!target || typeof target !== 'string') {
return {
valid: false,
message: 'Target must be a valid string'
};
}
// Limpiar espacios en blanco
const cleanTarget = target.trim();
if (cleanTarget.length === 0) {
return {
valid: false,
message: 'Target cannot be empty'
};
}
// Verificar si es una IP válida (IPv4 o IPv6)
if (ipRegex().test(cleanTarget)) {
// Validaciones adicionales para IPs
if (isPrivateOrReservedIP(cleanTarget)) {
return {
valid: false,
message: 'Private, loopback, or reserved IP addresses are not allowed'
};
}
return {
valid: true,
type: 'ip',
message: 'Valid IP address'
};
}
// Si no es IP, verificar si es un hostname válido
if (isValidHostname(cleanTarget)) {
// Verificar que no sea localhost o dominios locales
if (isLocalHostname(cleanTarget)) {
return {
valid: false,
message: 'Local hostnames are not allowed'
};
}
return {
valid: true,
type: 'hostname',
message: 'Valid hostname'
};
}
return {
valid: false,
message: 'Invalid IP address or hostname format'
};
}
function isPrivateOrReservedIP(ip) {
// Rangos de IPs privadas y reservadas que no deberíamos permitir
const privateRanges = [
/^127\./, // Loopback
/^10\./, // Private class A
/^172\.(1[6-9]|2[0-9]|3[01])\./, // Private class B
/^192\.168\./, // Private class C
/^169\.254\./, // Link-local
/^224\./, // Multicast
/^0\./, // Reserved
/^255\./, // Broadcast
/^::1$/, // IPv6 loopback
/^fe80:/, // IPv6 link-local
/^fc00:/, // IPv6 private
/^fd00:/ // IPv6 private
];
return privateRanges.some(range => range.test(ip));
}
function isValidHostname(hostname) {
// Verificar longitud
if (hostname.length > 253) {
return false;
}
// Patrón para hostname válido (RFC 1123)
const hostnameRegex = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
if (!hostnameRegex.test(hostname)) {
return false;
}
// Verificar que no termine con punto
if (hostname.endsWith('.')) {
return false;
}
// Verificar que cada parte del hostname no sea demasiado larga
const parts = hostname.split('.');
return parts.every(part => part.length <= 63 && part.length > 0);
}
function isLocalHostname(hostname) {
const localHostnames = [
'localhost',
'localhost.localdomain',
'local',
'internal',
'intranet'
];
const lowerHostname = hostname.toLowerCase();
// Verificar hostnames exactos
if (localHostnames.includes(lowerHostname)) {
return true;
}
// Verificar dominios .local
if (lowerHostname.endsWith('.local')) {
return true;
}
// Verificar si termina en .localhost
if (lowerHostname.endsWith('.localhost')) {
return true;
}
return false;
}
export function sanitizeTarget(target) {
if (typeof target !== 'string') {
return '';
}
return target.trim().toLowerCase();
}
export function isValidTimeout(timeout) {
const timeoutNum = parseInt(timeout);
return !isNaN(timeoutNum) && timeoutNum >= 1000 && timeoutNum <= 30000;
}
export function isValidCount(count) {
const countNum = parseInt(count);
return !isNaN(countNum) && countNum >= 1 && countNum <= 10;
}

38
src/middleware.js Archivo normal
Ver fichero

@@ -0,0 +1,38 @@
import { NextResponse } from 'next/server';
export function middleware(request) {
// Crear la respuesta
const response = NextResponse.next();
// Agregar headers de seguridad
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-XSS-Protection', '1; mode=block');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
// Headers específicos para API
if (request.nextUrl.pathname.startsWith('/api/')) {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type');
// Manejar preflight requests
if (request.method === 'OPTIONS') {
return new Response(null, { status: 200, headers: response.headers });
}
}
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};