新增偵測 aws ec2 的 ip

This commit is contained in:
2025-09-21 03:08:41 +08:00
parent b6356ed237
commit 8b3af6608e
5 changed files with 1012 additions and 16 deletions

View File

@@ -0,0 +1,59 @@
// =====================================================
// 智能連線清理 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { smartConnectionCleaner } from '@/lib/smart-connection-cleaner';
export async function POST(request: NextRequest) {
try {
console.log('🧠 收到智能清理請求');
// 執行智能清理
const result = await smartConnectionCleaner.smartCleanup(request);
return NextResponse.json({
success: result.success,
message: result.message,
data: {
killedCount: result.killedCount,
details: result.details,
timestamp: new Date().toISOString()
}
});
} catch (error) {
console.error('❌ 智能清理 API 錯誤:', error);
return NextResponse.json({
success: false,
error: '智能清理失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function GET(request: NextRequest) {
try {
console.log('📊 收到連線統計請求');
// 獲取連線統計
const stats = await smartConnectionCleaner.getConnectionStats();
return NextResponse.json({
success: true,
message: '連線統計獲取成功',
data: {
stats,
timestamp: new Date().toISOString()
}
});
} catch (error) {
console.error('❌ 連線統計 API 錯誤:', error);
return NextResponse.json({
success: false,
error: '獲取連線統計失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -0,0 +1,280 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, CheckCircle, AlertTriangle, RefreshCw, Trash2, BarChart3 } from 'lucide-react';
interface ConnectionStats {
total: number;
user: number;
infrastructure: number;
other: number;
details: Array<{
id: number;
host: string;
time: number;
state: string;
type: 'user' | 'infrastructure' | 'other';
}>;
}
interface CleanupResult {
success: boolean;
message: string;
data: {
killedCount: number;
details: {
userRealIP?: string;
infrastructureIPs?: string[];
cleanedConnections: Array<{
id: number;
host: string;
time: number;
state: string;
}>;
};
};
}
export default function SmartCleanupTestPage() {
const [stats, setStats] = useState<ConnectionStats | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 獲取連線統計
const fetchStats = async () => {
try {
setLoading(true);
const response = await fetch('/api/smart-cleanup');
const data = await response.json();
if (data.success) {
setStats(data.data.stats);
setMessage('連線統計更新成功');
setError('');
} else {
setError(data.error || '獲取連線統計失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 執行智能清理
const performSmartCleanup = async () => {
try {
setLoading(true);
const response = await fetch('/api/smart-cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const data: CleanupResult = await response.json();
if (data.success) {
setMessage(`智能清理完成: ${data.message}`);
setError('');
// 重新獲取統計
await fetchStats();
} else {
setError(data.error || '智能清理失敗');
}
} catch (err) {
setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時獲取統計
useEffect(() => {
fetchStats();
}, []);
// 獲取類型顏色
const getTypeColor = (type: 'user' | 'infrastructure' | 'other') => {
switch (type) {
case 'user': return 'default';
case 'infrastructure': return 'destructive';
case 'other': return 'secondary';
default: return 'outline';
}
};
// 獲取類型標籤
const getTypeLabel = (type: 'user' | 'infrastructure' | 'other') => {
switch (type) {
case 'user': return '用戶連線';
case 'infrastructure': return '基礎設施';
case 'other': return '其他';
default: return '未知';
}
};
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground">
IP
</p>
</div>
<div className="flex gap-2">
<Button
onClick={fetchStats}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
</Button>
<Button
onClick={performSmartCleanup}
disabled={loading}
variant="destructive"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
</Button>
</div>
</div>
{/* 連線統計概覽 */}
{stats && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<BarChart3 className="h-5 w-5" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="text-center">
<div className="text-2xl font-bold">{stats.total}</div>
<div className="text-sm text-muted-foreground"></div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-blue-600">{stats.user}</div>
<div className="text-sm text-muted-foreground"></div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-red-600">{stats.infrastructure}</div>
<div className="text-sm text-muted-foreground"></div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-gray-600">{stats.other}</div>
<div className="text-sm text-muted-foreground"></div>
</div>
</div>
</CardContent>
</Card>
)}
{/* 連線詳情 */}
{stats && stats.details.length > 0 && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2 max-h-96 overflow-y-auto">
{stats.details.map((conn, index) => (
<div key={index} className="flex items-center justify-between p-3 border rounded">
<div className="flex items-center gap-3">
<Badge variant={getTypeColor(conn.type)}>
{getTypeLabel(conn.type)}
</Badge>
<span className="font-mono text-sm">ID: {conn.id}</span>
<span className="text-sm text-muted-foreground">
{conn.host}
</span>
</div>
<div className="flex items-center gap-3">
<span className="text-sm">: {conn.time}s</span>
<span className="text-sm text-muted-foreground">
: {conn.state}
</span>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 功能說明 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<h4 className="font-semibold text-blue-600 mb-2"></h4>
<ul className="text-sm text-muted-foreground space-y-1">
<li> IP (61-227-253-171)</li>
<li> IP </li>
<li> </li>
<li> </li>
</ul>
</div>
<div>
<h4 className="font-semibold text-red-600 mb-2"></h4>
<ul className="text-sm text-muted-foreground space-y-1">
<li> AWS EC2 </li>
<li> Vercel </li>
<li> </li>
<li> </li>
</ul>
</div>
</div>
</CardContent>
</Card>
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle>使</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong>:</strong> </p>
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> Vercel/AWS </p>
<p> <strong>:</strong> </p>
</CardContent>
</Card>
{/* 訊息顯示 */}
{message && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</div>
);
}

View File

@@ -0,0 +1,313 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, Eye, RefreshCw, AlertTriangle, CheckCircle } from 'lucide-react';
interface VercelIPInfo {
smartDetection: {
detectedIP: string;
confidence: 'high' | 'medium' | 'low';
source: string;
isPublicIP: boolean;
allCandidates: string[];
isInfrastructureIP?: boolean;
isUserRealIP?: boolean;
infrastructureIPs?: string[];
userRealIPs?: string[];
};
headers: Record<string, string | null>;
nextRequestIP: string | undefined;
env: Record<string, string | undefined>;
allHeaders: Record<string, string>;
}
export default function VercelIPDebugPage() {
const [ipInfo, setIpInfo] = useState<VercelIPInfo | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 獲取 IP 調試信息
const fetchIPInfo = async () => {
try {
setLoading(true);
const response = await fetch('/api/debug-ip');
const data = await response.json();
if (data.success) {
setIpInfo(data.data);
if (data.data.smartDetection) {
const smartDetection = data.data.smartDetection;
setMessage(`Vercel IP 偵測結果: ${smartDetection.detectedIP} (可信度: ${smartDetection.confidence}, 來源: ${smartDetection.source})`);
} else {
setMessage('IP 調試信息更新成功');
}
setError('');
} else {
setError(data.error || '獲取 IP 調試信息失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時獲取 IP 信息
useEffect(() => {
fetchIPInfo();
}, []);
// 檢查是否為基礎設施 IP
const isInfrastructureIP = (ip: string): boolean => {
if (!ip) return false;
return ip.includes('ec2-') && ip.includes('.amazonaws.com');
};
// 檢查是否為用戶真實 IP
const isUserRealIP = (ip: string): boolean => {
if (!ip || ip === 'unknown') return false;
return !isInfrastructureIP(ip) && ip !== '::1' && ip !== '127.0.0.1';
};
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">Vercel IP 調</h1>
<p className="text-muted-foreground">
調 Vercel IP
</p>
</div>
<Button
onClick={fetchIPInfo}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
</Button>
</div>
{/* 智能偵測結果 */}
{ipInfo?.smartDetection && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Eye className="h-5 w-5" />
IP
</CardTitle>
<CardDescription>
IP IP
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<Badge
variant={
isUserRealIP(ipInfo.smartDetection.detectedIP) ? "default" :
isInfrastructureIP(ipInfo.smartDetection.detectedIP) ? "destructive" : "secondary"
}
className="text-lg px-3 py-1"
>
{ipInfo.smartDetection.detectedIP}
</Badge>
<Badge
variant={
ipInfo.smartDetection.confidence === 'high' ? "default" :
ipInfo.smartDetection.confidence === 'medium' ? "secondary" : "destructive"
}
className="text-lg px-3 py-1"
>
: {ipInfo.smartDetection.confidence}
</Badge>
<Badge variant="outline" className="text-lg px-3 py-1">
: {ipInfo.smartDetection.source}
</Badge>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<p className="text-sm font-medium mb-2"> IP:</p>
<div className="flex flex-wrap gap-2">
{ipInfo.smartDetection.userRealIPs?.map((ip, index) => (
<Badge
key={index}
variant="default"
className="text-sm"
>
{ip}
</Badge>
)) || <span className="text-muted-foreground text-sm"></span>}
</div>
</div>
<div>
<p className="text-sm font-medium mb-2"> IP ():</p>
<div className="flex flex-wrap gap-2">
{ipInfo.smartDetection.infrastructureIPs?.map((ip, index) => (
<Badge
key={index}
variant="destructive"
className="text-sm"
>
{ip}
</Badge>
)) || <span className="text-muted-foreground text-sm"></span>}
</div>
</div>
</div>
</CardContent>
</Card>
)}
{/* 請求標頭分析 */}
{ipInfo && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
HTTP IP
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{Object.entries(ipInfo.headers).map(([key, value]) => {
if (!value) return null;
const isInfra = isInfrastructureIP(value);
const isUser = isUserRealIP(value);
return (
<div key={key} className="flex items-center justify-between p-3 border rounded">
<div className="flex-1">
<span className="font-medium text-sm">{key}:</span>
<div className="mt-1">
<Badge
variant={
isUser ? "default" :
isInfra ? "destructive" : "outline"
}
className="text-sm"
>
{value}
</Badge>
<div className="flex gap-2 mt-1">
{isUser && <Badge variant="default" className="text-xs"> IP</Badge>}
{isInfra && <Badge variant="destructive" className="text-xs"> IP</Badge>}
</div>
</div>
</div>
</div>
);
})}
</div>
</CardContent>
</Card>
)}
{/* 環境信息 */}
{ipInfo && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
Vercel
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{Object.entries(ipInfo.env).map(([key, value]) => (
<div key={key} className="flex items-center justify-between p-2 border rounded">
<span className="font-medium text-sm">{key}:</span>
<span className="text-sm text-muted-foreground">
{value || 'undefined'}
</span>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 問題診斷 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5" />
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{ipInfo?.smartDetection && (
<>
{isInfrastructureIP(ipInfo.smartDetection.detectedIP) && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
<strong>:</strong> Vercel/AWS IP IP
<br />
<strong>:</strong> x-forwarded-for IP
</AlertDescription>
</Alert>
)}
{isUserRealIP(ipInfo.smartDetection.detectedIP) && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
<strong>:</strong> IP
</AlertDescription>
</Alert>
)}
{!isUserRealIP(ipInfo.smartDetection.detectedIP) && !isInfrastructureIP(ipInfo.smartDetection.detectedIP) && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
<strong>:</strong> IP
<br />
<strong>:</strong>
</AlertDescription>
</Alert>
)}
</>
)}
</CardContent>
</Card>
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle>使</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong> IP:</strong> Vercel/AWS IP IP</p>
<p> <strong> IP:</strong> IP </p>
<p> <strong>x-forwarded-for:</strong> IP "用戶IP,代理IP"</p>
<p> <strong>:</strong> IP</p>
</CardContent>
</Card>
{/* 訊息顯示 */}
{message && (
<Alert>
<Database className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<Eye className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</div>
);
}