新增偵測 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,280 @@
// =====================================================
// 智能連線清理器
// =====================================================
import mysql from 'mysql2/promise';
import { db } from './database';
import { smartIPDetector } from './smart-ip-detector';
import { NextRequest } from 'next/server';
export interface CleanupResult {
success: boolean;
killedCount: number;
message: string;
details: {
userRealIP?: string;
infrastructureIPs?: string[];
cleanedConnections: Array<{
id: number;
host: string;
time: number;
state: string;
}>;
};
}
export class SmartConnectionCleaner {
private static instance: SmartConnectionCleaner;
public static getInstance(): SmartConnectionCleaner {
if (!SmartConnectionCleaner.instance) {
SmartConnectionCleaner.instance = new SmartConnectionCleaner();
}
return SmartConnectionCleaner.instance;
}
// 智能清理連線
public async smartCleanup(request: NextRequest): Promise<CleanupResult> {
try {
// 1. 使用智能 IP 偵測器獲取真實 IP
const ipDetection = smartIPDetector.detectClientIP(request);
const userRealIP = ipDetection.detectedIP;
console.log('🧠 智能清理開始:', {
detectedIP: userRealIP,
confidence: ipDetection.confidence,
source: ipDetection.source,
isUserRealIP: ipDetection.isUserRealIP,
infrastructureIPs: ipDetection.infrastructureIPs
});
// 2. 建立資料庫連線
const connection = await db.getConnection();
let killedCount = 0;
const cleanedConnections: Array<{
id: number;
host: string;
time: number;
state: string;
}> = [];
try {
// 3. 獲取所有相關連線
const [allConnections] = await connection.execute(`
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO
FROM information_schema.PROCESSLIST
WHERE USER = ?
ORDER BY TIME DESC
`, [process.env.DB_USER || 'A999']);
console.log(`🔍 找到 ${allConnections.length} 個總連線`);
// 4. 分類連線
const userConnections = allConnections.filter((conn: any) =>
this.isUserConnection(conn.HOST, userRealIP)
);
const infrastructureConnections = allConnections.filter((conn: any) =>
this.isInfrastructureConnection(conn.HOST)
);
console.log(`👤 用戶連線: ${userConnections.length}`);
console.log(`🏗️ 基礎設施連線: ${infrastructureConnections.length}`);
// 5. 清理用戶連線(優先)
if (userConnections.length > 0) {
console.log(`🧹 開始清理用戶連線 (IP: ${userRealIP})`);
for (const conn of userConnections) {
if (conn.ID !== connection.threadId) {
try {
await connection.execute(`KILL ${conn.ID}`);
console.log(`💀 已殺死用戶連線 ${conn.ID} (HOST: ${conn.HOST})`);
killedCount++;
cleanedConnections.push({
id: conn.ID,
host: conn.HOST,
time: conn.TIME,
state: conn.STATE || 'Sleep'
});
} catch (error: any) {
console.log(`⚠️ 無法殺死用戶連線 ${conn.ID}: ${error.message}`);
}
}
}
}
// 6. 清理基礎設施連線(可選,根據配置)
const shouldCleanInfrastructure = process.env.CLEAN_INFRASTRUCTURE_CONNECTIONS === 'true';
if (shouldCleanInfrastructure && infrastructureConnections.length > 0) {
console.log(`🧹 開始清理基礎設施連線`);
for (const conn of infrastructureConnections) {
if (conn.ID !== connection.threadId) {
try {
await connection.execute(`KILL ${conn.ID}`);
console.log(`💀 已殺死基礎設施連線 ${conn.ID} (HOST: ${conn.HOST})`);
killedCount++;
cleanedConnections.push({
id: conn.ID,
host: conn.HOST,
time: conn.TIME,
state: conn.STATE || 'Sleep'
});
} catch (error: any) {
console.log(`⚠️ 無法殺死基礎設施連線 ${conn.ID}: ${error.message}`);
}
}
}
}
console.log(`✅ 智能清理完成: 共清理 ${killedCount} 個連線`);
return {
success: true,
killedCount,
message: `智能清理完成: 共清理 ${killedCount} 個連線`,
details: {
userRealIP: userRealIP !== 'unknown' ? userRealIP : undefined,
infrastructureIPs: ipDetection.infrastructureIPs,
cleanedConnections
}
};
} finally {
connection.release();
}
} catch (error) {
console.error('❌ 智能清理失敗:', error);
return {
success: false,
killedCount: 0,
message: `智能清理失敗: ${error instanceof Error ? error.message : '未知錯誤'}`,
details: {
cleanedConnections: []
}
};
}
}
// 檢查是否為用戶連線
private isUserConnection(host: string, userIP: string): boolean {
if (!host || !userIP || userIP === 'unknown') return false;
// 直接匹配用戶 IP
if (host.includes(userIP)) return true;
// 匹配用戶 IP 的變體格式
const ipVariants = [
userIP,
userIP.replace(/\./g, '-'), // 61.227.253.171 -> 61-227-253-171
userIP.replace(/\./g, '_'), // 61.227.253.171 -> 61_227_253_171
];
return ipVariants.some(variant => host.includes(variant));
}
// 檢查是否為基礎設施連線
private isInfrastructureConnection(host: string): boolean {
if (!host) return false;
// AWS EC2 實例
if (host.includes('ec2-') && host.includes('.amazonaws.com')) return true;
// 其他基礎設施模式
const infrastructurePatterns = [
'.amazonaws.com',
'.vercel.app',
'vercel',
'cloudflare',
'fastly.com',
'cloudfront.net'
];
return infrastructurePatterns.some(pattern => host.includes(pattern));
}
// 獲取連線統計
public async getConnectionStats(): Promise<{
total: number;
user: number;
infrastructure: number;
other: number;
details: Array<{
id: number;
host: string;
time: number;
state: string;
type: 'user' | 'infrastructure' | 'other';
}>;
}> {
try {
const connection = await db.getConnection();
try {
const [connections] = await connection.execute(`
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO
FROM information_schema.PROCESSLIST
WHERE USER = ?
ORDER BY TIME DESC
`, [process.env.DB_USER || 'A999']);
const stats = {
total: connections.length,
user: 0,
infrastructure: 0,
other: 0,
details: [] as Array<{
id: number;
host: string;
time: number;
state: string;
type: 'user' | 'infrastructure' | 'other';
}>
};
for (const conn of connections) {
let type: 'user' | 'infrastructure' | 'other' = 'other';
if (this.isInfrastructureConnection(conn.HOST)) {
type = 'infrastructure';
stats.infrastructure++;
} else if (this.isUserConnection(conn.HOST, 'unknown')) {
type = 'user';
stats.user++;
} else {
stats.other++;
}
stats.details.push({
id: conn.ID,
host: conn.HOST,
time: conn.TIME,
state: conn.STATE || 'Sleep',
type
});
}
return stats;
} finally {
connection.release();
}
} catch (error) {
console.error('❌ 獲取連線統計失敗:', error);
return {
total: 0,
user: 0,
infrastructure: 0,
other: 0,
details: []
};
}
}
}
// 導出單例實例
export const smartConnectionCleaner = SmartConnectionCleaner.getInstance();

View File

@@ -43,6 +43,51 @@ export class SmartIPDetector {
return true;
}
// 檢查是否為基礎設施 IPVercel、AWS、Cloudflare 等)
private isInfrastructureIP(ip: string): boolean {
if (!ip) return false;
// Vercel/AWS EC2 實例
if (ip.includes('ec2-') && ip.includes('.compute-1.amazonaws.com')) return true;
if (ip.includes('ec2-') && ip.includes('.amazonaws.com')) return true;
// AWS 其他服務
if (ip.includes('.amazonaws.com')) return true;
// Vercel 相關
if (ip.includes('vercel')) return true;
// Cloudflare 相關(但 cf-connecting-ip 是我們想要的)
if (ip.includes('cloudflare') && !ip.includes('cf-connecting-ip')) return true;
// 其他常見的 CDN/代理服務
const infrastructurePatterns = [
'fastly.com',
'cloudfront.net',
'akamai.net',
'maxcdn.com',
'keycdn.com'
];
return infrastructurePatterns.some(pattern => ip.includes(pattern));
}
// 檢查是否為用戶真實 IP
private isUserRealIP(ip: string): boolean {
if (!ip || ip === 'unknown') return false;
// 不是基礎設施 IP
if (this.isInfrastructureIP(ip)) return false;
// 是公網 IP
if (!this.isPublicIP(ip)) return false;
// 是有效的 IP 格式
if (!this.isValidIP(ip)) return false;
return true;
}
// 從 x-forwarded-for 解析 IP
private parseForwardedFor(forwarded: string): string[] {
if (!forwarded) return [];
@@ -111,20 +156,20 @@ export class SmartIPDetector {
let confidence: 'high' | 'medium' | 'low' = 'low';
let source = 'unknown';
// 優先級 1: Cloudflare IP (最高可信度)
// 優先級 1: Cloudflare IP (最高可信度) - 但要是用戶真實 IP
const cfIP = uniqueCandidates.find(ip => sources[ip] === 'cf-connecting-ip');
if (cfIP && this.isPublicIP(cfIP)) {
if (cfIP && this.isUserRealIP(cfIP)) {
selectedIP = cfIP;
confidence = 'high';
source = 'cf-connecting-ip';
}
// 優先級 2: 其他代理標頭中的公網 IP
// 優先級 2: 其他代理標頭中的用戶真實 IP
if (selectedIP === 'unknown') {
const proxyHeaders = ['x-real-ip', 'x-client-ip', 'x-cluster-client-ip'];
for (const header of proxyHeaders) {
const ip = uniqueCandidates.find(candidate => sources[candidate] === header);
if (ip && this.isPublicIP(ip)) {
if (ip && this.isUserRealIP(ip)) {
selectedIP = ip;
confidence = 'high';
source = header;
@@ -133,32 +178,45 @@ export class SmartIPDetector {
}
}
// 優先級 3: x-forwarded-for 中的第一個公網 IP
// 優先級 3: x-forwarded-for 中的第一個用戶真實 IP
if (selectedIP === 'unknown') {
const forwardedIPs = uniqueCandidates.filter(ip => sources[ip] === 'x-forwarded-for');
const publicForwardedIP = forwardedIPs.find(ip => this.isPublicIP(ip));
if (publicForwardedIP) {
selectedIP = publicForwardedIP;
const userRealIP = forwardedIPs.find(ip => this.isUserRealIP(ip));
if (userRealIP) {
selectedIP = userRealIP;
confidence = 'medium';
source = 'x-forwarded-for';
}
}
// 優先級 4: 任何公網 IP
// 優先級 4: 任何用戶真實 IP
if (selectedIP === 'unknown') {
const publicIP = uniqueCandidates.find(ip => this.isPublicIP(ip));
const userRealIP = uniqueCandidates.find(ip => this.isUserRealIP(ip));
if (userRealIP) {
selectedIP = userRealIP;
confidence = 'medium';
source = sources[userRealIP] || 'unknown';
}
}
// 優先級 5: 任何公網 IP非基礎設施
if (selectedIP === 'unknown') {
const publicIP = uniqueCandidates.find(ip =>
this.isPublicIP(ip) && !this.isInfrastructureIP(ip)
);
if (publicIP) {
selectedIP = publicIP;
confidence = 'medium';
confidence = 'low';
source = sources[publicIP] || 'unknown';
}
}
// 優先級 5: 任何非本地 IP
// 優先級 6: 任何非本地 IP(非基礎設施)
if (selectedIP === 'unknown') {
const nonLocalIP = uniqueCandidates.find(ip =>
ip !== '::1' && ip !== '127.0.0.1' && !ip.startsWith('192.168.') &&
!ip.startsWith('10.') && !ip.startsWith('172.')
ip !== '::1' && ip !== '127.0.0.1' &&
!ip.startsWith('192.168.') && !ip.startsWith('10.') && !ip.startsWith('172.') &&
!this.isInfrastructureIP(ip)
);
if (nonLocalIP) {
selectedIP = nonLocalIP;
@@ -167,7 +225,7 @@ export class SmartIPDetector {
}
}
// 優先級 6: 第一個候選 IP
// 優先級 7: 第一個候選 IP(最後選擇)
if (selectedIP === 'unknown' && uniqueCandidates.length > 0) {
selectedIP = uniqueCandidates[0];
confidence = 'low';
@@ -182,7 +240,13 @@ export class SmartIPDetector {
isPublicIP: this.isPublicIP(selectedIP)
};
console.log('🎯 IP 偵測結果:', result);
console.log('🎯 IP 偵測結果:', {
...result,
isInfrastructureIP: this.isInfrastructureIP(selectedIP),
isUserRealIP: this.isUserRealIP(selectedIP),
infrastructureIPs: uniqueCandidates.filter(ip => this.isInfrastructureIP(ip)),
userRealIPs: uniqueCandidates.filter(ip => this.isUserRealIP(ip))
});
return result;
}